Implementing drag-and-drop operations in vb.net

Source: Internet
Author: User
Tags integer
The first time in the CSDN article, I hope that everyone help to push the top, to encourage beginners, thank you http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/ html/vbtchimpdragdrop.asp implement drag-and-drop operations in vb.net implementing Drag and drop in Visual Basic. NET Steve Hoag Visual Basic®.net Tea M Microsoft Corporation September 2003 Summary: This article describes how to implement drag-and-drop operations in vb.net the introduction of Windows users are generally divided into two categories: a kind of habit of keyboard operation, a kind of habit with the mouse operation. Programmers typically provide keyboard shortcuts (underlined in commands or letters) or shortcuts (with CTRL plus letter combinations) to take care of users who are accustomed to keyboards, but those who are users of the mouse are ignored. Because programmers are generally used to using keyboards, it is understandable that their emphasis on keyboard manipulation is possible, but each programmer should also consider providing mouse support. One thing the mouse user expects is to be able to implement drag-and-drop in the application. If you notice some large applications or Windows themselves, drag-and-drop operations are almost everywhere. For example, a user might have been accustomed to dragging and dropping files in Windows Explorer, or dragging and dropping text in Word. While drag-and-drop operations can be seen everywhere, only a handful of programmers implement drag-and-drop functionality in the programs they write, most likely because they think implementation drag-and-drop might be more difficult than expected. This article enumerates examples of how to move text, pictures, or files between windows, between forms, and even between applications, showing that dragging and dropping in vb.net is very easy to achieve. Drag and drop is actually like copying sticky with the mouse, so you have to have a source that can be copied or moved, and a destination to paste. During both of these operations, the data is stored in memory. Copying and pasting is a clipping version, and drag-and-drop is a DataObject object that is essentially a private clipboard. The following is a typical time series for a hold operation: 1, drag (dragging) is initialized by invoking the DoDragDrop method of the source control, and DoDragDrop has two parameter data specifying the allowedeffects that will be transmitted. Specifies that the allowed operation (copy or move) automatically creates a new DataObject object 2 and then fires the GiveFeedback event in turn. In mostIn several cases, you don't have to worry about givefeedback events, but if you want to customize the mouse pointer in the drag-and-drop process, you can add your code to these places. 3. Any control that has a AllowDrop property and is set to true is an implied drop object. The AllowDrop property can be set in the Properties window at design time, or it can be loaded automatically in the Form_Load event. 4. When the mouse is moved to a control, it fires the DragEnter event of the control at the same time. The GetDataPresent method is used to confirm that the dragged data is suitable for the target control, and the effect property is used to display the appropriate mouse pointer. 5. If the user releases the mouse on a valid target control, it also fires the DragDrop event. The code in the DragDrop event handle frees the data from the DataObject object and displays it in the target control. What is the change from VB6 to vb.net? (slightly) a simple but useful scenario for dragging-and-dropping text drag-and-drop operations is to copy text from a TextBox control to another TextBox control. Of course you can do it with just the keyboard (CTRL + C and CTRL + V), but the drag-and-drop is simpler because it only needs to be moved by the mouse. 1. Add two text boxes to a form and set the AllowDrop property of the second TextBox control to True to add the following code. Private mouseisdown as Boolean = False private Sub textbox1_mousedown (ByVal sender as Object, ByVal e as _ system.windows. Forms.mouseeventargs) Handles Textbox1.mousedown ' Set a flag to show ' This mouse is down. Mouseisdown = True End Sub Private sub Textbox1_mousemove (ByVal sender as Object, ByVal e As _ System.Windows.Forms.MouseE Ventargs) Handles textbox1.mousemove If mouseisdown Then ' Initiate dragging. Textbox1.dodragdrop (TextBox1.Text, dragdropeffects.copy) end If Mouseisdown = False End Sub Private sub Textbox2_dragenter (ByVal sender as Object, ByVal e As _ system.windows.forms.d Rageventargs) Handles textbox2.dragenter ' Check The format of the data being dropped. If (E.data.getdatapresent (dataformats.text)) Then ' Display the copy cursor. e.effect = dragdropeffects.copy Else ' Display the No-drop cursor. E.effect = DragDropEffects.None End If End Sub Private sub Textbox2_dragdrop (ByVal sender as Object, ByVal e As _ SYSTEM.W indows. Forms.drageventargs) Handles Textbox2.dragdrop ' Paste the text. TextBox2.Text = e.Data.GetData (DataFormats. End Sub In the example above, the MouseDown event is used to determine whether the mouse is pressed, and the DoDragDrop method is used in the MouseMove event. Although you can initialize drag in the MouseDown event, doing so will bring unexpected results. The No-drag pointer is displayed when the user clicks on the control. The DoDragDrop method has two parameter data, and this example represents the Text property of the first TextBox. Allowedeffects, this example is only allowed to replicate. The MOUSEISDOWN flag is set to False in the MouseMove event, although this example is not necessary, but if you have many controls that support drag-and-drop, you will get a Run-time exception. In the DragEnter event, the GetDataPresent method checks the data format being dragged, in this case the text, so the effect property is set to copy and the copy pointer is also displayed. In the DragDrop event, the GetData method is used to obtain text from the DataObjectand send it to the target text box. Drag a picture although dragging and dropping pictures is not as often used as drag and drop text, it is still useful in many applications. In fact, there is no difference between the two, but the data type has changed. 1, add two PictureBox controls in the form. 2. Add the following code in the Code form Private Sub Form1_Load (ByVal sender as System.Object, ByVal e As _ System.EventArgs) Handles MyBase.Load ' Enable dropping. Picturebox2.allowdrop = True End Sub Private sub Picturebox1_mousedown (ByVal sender as Object, ByVal e As _ system.windows . Forms.mouseeventargs) Handles Picturebox1.mousedown If not picturebox1.image are nothing Then ' Set a flag Mouse is down. M_mouseisdown = True End If End Sub Private sub Picturebox1_mousemove (ByVal sender as Object, ByVal e as _ system.windows. Forms.mouseeventargs) Handles picturebox1.mousemove If m_mouseisdown Then ' Initiate dragging and allow either copy or MOV E. Picturebox1.dodragdrop (pictureBox1.Image, dragdropeffects.copy Or _ DragDropEffects.Move) End If M_MouseIsDown = False End Sub Private sub Picturebox2_dragenter (ByVal sender as Object, ByVal e As _ System.Windows.Forms.DragEventArgs) H AnDLEs picturebox2.dragenter If e.data.getdatapresent (dataformats.bitmap) Then ' Check for the CTRL key. If e.keystate = 9 Then e.effect = dragdropeffects.copy Else e.effect = DragDropEffects.Move End If Else e.effect = Dragdro Peffects.none End If End Sub Private sub Picturebox2_dragdrop (ByVal sender as Object, ByVal e As _ System.Windows.Forms.Dr Ageventargs) Handles Picturebox2.dragdrop ' Assign the image to the PictureBox. Picturebox2.image = e.Data.GetData (dataformats.bitmap) ' If the CTRL key is not pressed, delete the source picture. If not e.keystate = 8 Then picturebox1.image = ' Nothing ' If End Sub note in the example above the AllowDrop property of the second PictureBox control is set in the Form1_Load event , because the design-time PictureBox does not have the AllowDrop attribute. In the MouseDown event, the code first detects whether there is a picture to assign to PictureBox, and if not, the next click will cause an unexpected surprise when you move the picture. It should also be noted that the code detects whether the CTRL key is pressed in the DragEnter and DragDrop events to determine whether to copy or move the picture. Why is the value different? In the DragEnter event, when the left mouse button is pressed, the resulting value is 1, with the CTRL value of 8, which values 9. See Keystate Enumeration List Drageventargs.keystate Property (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwindowsformsdrageventargsclasskeystatetopic.asp). So far, these two examples deal with drag-and-drop between different controls on the same form, but they also apply to different forms on the same application. Dragging a file to drag and drop in Windows is usually copying or moving files, and Windows fully supports this feature, and this is also the preferred way for many users to manipulate files. In addition, users have been accustomed to dragging files to a program to open the file, like dragging a doc file to Word to open. In this example, the ListBox control is manipulated using a file dragged from Windows Explorer. Add a ListBox control to the form and set its AllowDrop property to True and add the following code: Private Sub listbox1_dragenter (ByVal sender as Object, ByVal e As _ syste M.windows.forms.drageventargs) Handles listbox1.dragenter If e.data.getdatapresent (dataformats.filedrop) Then E. Effect = DragDropEffects.All End If End Sub Private sub listBox1_DragDrop (ByVal sender as Object, ByVal e As _ System.wind oWS. Forms.drageventargs) Handles listbox1.dragdrop If e.data.getdatapresent (dataformats.filedrop) Then Dim MyFiles () as String Dim i as Integer ' Assign the files to an array. Myfiles = e.Data.GetData (dataformats.filedrop) ' Loop through the array and add the files to the list. For i = 0 to myfiles.length-1 ListBox1.Items.Add (myfiles (i)) The Next end If The Sub you may have noticed dragThe effect property in the Enter event is set to DragDropEffects.All. Because the file itself is not actually copied or moved, it does not matter which allowedeffects the source control is set to, so specifying all is OK for any filedrop. In the example above, the FileDrop format contains the full path of each dragged file. The following example describes a special case of drag-and-drop: dragging and dropping between two lists. Another case of drag-and-drop between tables is moving items from one list to another. In this case, drag and drop will become simpler. Add two ListView controls to the form, and set their allowdrop, MultiSelect, view properties to True, true, and List respectively. and add the following code: Private Sub Listview_itemdrag (ByVal sender as Object, ByVal e As _ System.Windows.Forms.ItemDragEventArgs) Handle S Listview1.itemdrag, _ Listview2.itemdrag Dim myitem As ListViewItem Dim myitems (Sender. selecteditems.count-1) as ListViewItem Dim i as Integer = 0 ' Loop though the SelectedItems collection for the source. For Each myitem in sender. SelectedItems ' Add the ListViewItem to the array of ListViewItems. MyItems (i) = myitem i = i + 1 Next ' Create a DataObject containg the array of ListViewItems. Sender. DoDragDrop (New _ DataObject ("System.Windows.Forms.ListViewItem ()", myitems), _ DragDropEffects.Move) End Sub Private Sub Listview_dragenter (ByVal sender as Object, ByVal e As _ System. Windows.Forms.DragEventArgs) Handles Listview1.dragenter, _ Listview2.dragenter ' Check for the custom DataFormat Listvie Witem Array. If e.data.getdatapresent ("System.Windows.Forms.ListViewItem ()") Then e.effect = dragdropeffects.move Else e.effect = DragDropEffects.None End If End Sub Private sub Listview_dragdrop (ByVal sender as Object, ByVal e As _ System.Windows.Form S.drageventargs) Handles Listview1.dragdrop, _ Listview2.dragdrop Dim myitem As ListViewItem Dim myitems () as ListViewItem = _ e.Data.GetData ("System.Windows.Forms.ListViewItem ()") Dim i as Integer = 0 for Each myitem In myitems ' Add the item to the target list. Sender. Items.Add (MyItems (i). Text) ' Remove the item from the source list. If Sender is ListView1 Then ListView2.Items.Remove (ListView2.SelectedItems.Item (0)) Else ListView1.Items.Remove ( ListView1.SelectedItems.Item (0)) End If i = i + 1 Next end Sub You may not understand why this example uses the ListView control instead of the ListBox control, which is a good question because the listbox controls The pieces do not support multiple drag and drop. There is a ItemDrag event for the ListView and TreeView controls. In the example above, an itemThe drag event handle covers two controls and is listed in the Handles clause. The sender parameter indicates which control is initializing the drag. Because the DataFormats class does not have a ListViewItem type member, the data must be passed to a system type. ItemDrag creates an array of listviewitem types and iterates through the SelectedItem collection with a loop. In the DoDragDrop method, a new DataObject is created and the array is used to manipulate it. You can use this method to drag and drop any system type. Conclusion: As you can see from these examples, it is not difficult to add drag-and-drop operations to the application. Once you understand these basic techniques, you can add drag and drop code to your own program.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.