Comprehensive Understanding of Drag and Drop Operations in C #

Source: Internet
Author: User
With the launch of the desktop system, the use of the Drag and Drop operation of the mouse has become more and more popular among readers due to its simplicity and directness. to cater to this trend, more and more programmers use drag-and-drop operations in their own programs. The drag-and-drop operation is convenient for users of the program. However, the drag-and-drop operation is still troublesome in the design of the program, or even difficult. Many programmers have a bit worried about it. This article introduces how to handle drag-and-drop operations in C # based on Microsoft's latest. Net Programming Language C.

 

In this article, we use two representative components, the TreeView component and the ListView component, which are frequently used in drag-and-drop operations, drag and Drop between them to illustrate such problems. Before performing the drag-and-drop operation, you must set the "AllowDrop" attribute value of the component to "True" because this attribute determines whether the component can perform the drag-and-drop operation.

I. The software environment for program design and operation described in this article:

(1). Microsoft Windows 2000 Server Edition

(2). Net FrameWork SDK Beta 2

2. Drag and Drop Operations from the TreeView component to the ListView component:

To complete this drag-and-drop operation, you must handle three types of events: "ItemDrag", "DragEnter", and "DragDrop ". Only the first event is triggered in the source component, and the other two events are triggered in the target component. The "ItemDrag" event is triggered when you drag the component, the "DragEnter" event is triggered when you drag data into the target component area, and the "DragDrop" event is triggered when you place the dragged data in the target component area. The following describes the operation sequence of Drag and Drop Operations in detail:

(1). Start the Drag operation:

The "DoDragDrop" method is used to open the first step of the drag-and-drop operation. The syntax of the "DoDragDrop" method is:

DoDragDrop (object data, DragDropEffects allowedEffects );

The second parameter indicates the final effect of the drag-and-drop operation, because the drag-and-drop operation sometimes achieves the effect of dragging the content in the source component to the target component, this effect is "Move". Sometimes the drag-and-drop effect is to add the dragged data to the target component, which has no effect on the content of the source component. This effect is "Copy ". Of course, whether it is "Move" or "Copy", this must be achieved through specific programming. setting these effects only tells the operating system the type of drag-and-drop operations you perform, to set a specific icon for the drag-and-drop operation. In this example, the specific implementation code for the "Drag and Drop" operation is as follows:

Private void treeviewincluitemdrag (object sender, ItemDragEventArgs e)
{
String strItem = e. Item. ToString ();
// Start the "Drag" Operation
DoDragDrop (strItem, DragDropEffects. Copy | DragDropEffects. Move );
}

In the code above, we defined the drag-and-drop data type as a string. In fact, there are many types of drag-and-drop data, you can modify the first parameter of the "DoDragDrop" method to set the data type you want to drag and drop, such as bitmap or something else.

(2). The target component allows drag and drop operations:

Since you have started the drag-and-drop operation, you must also tell the target component you want to drag and drop to accept the data you drag and drop. The "DragEnter" event can be handled exactly. In the following code, we determine whether to accept drag-and-drop by judging the drag-and-drop data type. If it is a string, yes. Otherwise, no. The Code is as follows:

Private void listviewincludragenter (object sender, DragEventArgs e)
{
// Determine whether the currently dragged data is a string. If yes, the drag string copies the target component.
If (e. Data. GetDataPresent (DataFormats. Text ))
E. Effect = DragDropEffects. Move;
Else
E. Effect = DragDropEffects. None;
}

(3). Obtain the drag-and-drop string and add the following content to the target component:

The processing process of this step is very clear and should be divided into two steps. First, we should get the drag-and-drop string, and then add the project with this string as the title in the target component. Of course, it must be in the corresponding position. The following code implements the two steps:

Private void listviewincludragdrop (object sender, DragEventArgs e)
{
String dummy = "temp ";
// Obtain the string to be dragged in the Drag operation.
String s = (string) e. Data. GetData (dummy. GetType ());
S = s. Substring (s. IndexOf (":") + 1). Trim ();
Position. X = e. X;
Position. Y = e. Y;
Position = listView1.PointToClient (Position );
// Add a project with the title of this string to the target component
ListView1.Items. Add (new ListViewItem (s, 0 ));
}

 

By programming these three events, you have completed the drag-and-drop operation from the TreeView component to the ListView component.

3. Drag and Drop Operations from the ListView component to the TreeView component:

The drag-and-drop operations from the ListView component to the TreeView component are similar to those from the TreeView component to the ListView component. They are also handled through three events: "ItemDrag", "DragEnter", and "DragDrop, the details are as follows:

(1). Start the Drag operation:

This is no essentially different from the former, but before the start of this drag-and-drop operation, some logic judgments were added to make the program more stable and allowed. The implementation code is as follows:

Private void listviewincluitemdrag (object sender, ItemDragEventArgs e)
{
// Right-click or press
If (e. Button = MouseButtons. Right) return;
Int nTotalSelected = listView1.SelectedIndices. Count;
// Determine whether a project exists in the component
If (nTotalSelected <= 0) return;
IEnumerator selCol = listView1.SelectedItems. GetEnumerator ();
SelCol. MoveNext ();
ListViewItem lvi = (ListViewItem) selCol. Current;
String mDir = "";
For (int I = 0; I <lvi. SubItems. Count; I ++)
MDir + = lvi. SubItems [I]. Text + ",";
String str = mDir. Substring (0, mDir. Length-1 );
If (str = "") return;
// Drag and drop the string in the component
ListView1.DoDragDrop (str, DragDropEffects. Copy | DragDropEffects. Move );
}

 

(2). The target component allows drag and drop operations:

This step is the most consistent for drag-and-drop operations. Unless the Data Type of the drag-and-drop operation is changed, there is no need to modify the source code as follows:

Private void treeviewincludragenter (object sender, DragEventArgs e)
{
// Determine whether the currently dragged data is a string. If yes, the drag string copies the target component.
If (e. Data. GetDataPresent (DataFormats. Text ))
E. Effect = DragDropEffects. Copy;
Else
E. Effect = DragDropEffects. None;
}

(3). Obtain the drag-and-drop string and add the following content to the target component:

For different components that perform drag-and-drop operations, the implementation methods for obtaining the drag-and-drop data are different. This step is no exception, but it is always the same. You can master the steps and key points of the program design, in addition to the spirit of exploration and research, this problem should be solved. The following is the program code to achieve this step:

Private void treeviewincludragdrop (object sender, DragEventArgs e)
{
// Obtain the string to be dragged in the Drag operation.
String dummy = "temp ";
String s = (string) e. Data. GetData (dummy. GetType ());
S = s. Substring (s. IndexOf (":") + 1). Trim ();
Position. X = e. X;
Position. Y = e. Y;
Position = treeView1.PointToClient (Position );
TreeNode DropNode = this. treeView1.GetNodeAt (Position );
// Add a project with the title of this string to the target component
If (DropNode! = Null)
{
TreeNode DragNode = new TreeNode (s );
TreeView1.Nodes. Insert (DropNode. Index + 1, DragNode );
}
}

 

4. complete source code (dragdrop. cs) for drag-and-drop operations by two components ):

After mastering the above steps, you can get the complete code for the two components to drag and drop each other and the running interface of the compiled program, as shown below:

 

 

Figure 01: program running interface with two components dragging and dropping each other

The code for dragdrop. cs is as follows:

Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;
// The namespace used in the import program
Public class Form1: Form
{
Private TreeView treeView1;
Private Point Position = new Point (0, 0 );
// Bool lv1_mdown = false;
Private ListView listView1;
Private System. ComponentModel. Container components = null;
Public Form1 ()
{
InitializeComponent ();
// Initialize components in the form
}
// Clear various resources used in the program
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
Private void InitializeComponent ()
{
ListViewItem listViewItem1 = new ListViewItem ("Item01 ");
ListViewItem listViewItem2 = new ListViewItem ("Item02 ");
TreeView1 = new TreeView ();
ListView1 = new ListView ();
SuspendLayout ();
// This attribute must be set to "true" for drag-and-drop operations
TreeView1.AllowDrop = true;
TreeView1.ImageIndex =-1;
TreeView1.Location = new Point (48, 40 );
TreeView1.Name = "treeView1 ";
// Add the initialized node to the TreeView component
TreeView1.Nodes. Add (new TreeNode ("Node 01 "));
TreeView1.Nodes. Add (new TreeNode ("Node 02 "));
TreeView1.SelectedImageIndex =-1;
TreeView1.Size = new Size (121,144 );
TreeView1.TabIndex = 0;
TreeView1.DragEnter + = new DragEventHandler (treeviewincludragenter );
TreeView1.ItemDrag + = new ItemDragEventHandler (treeviewincluitemdrag );
TreeView1.DragDrop + = new DragEventHandler (treeviewincludragdrop );
// This attribute must be set to "true" for drag-and-drop operations
ListView1.AllowDrop = true;
// Add a project to the ListView component
ListView1.Items. Add (listViewItem1 );
ListView1.Items. Add (listViewItem2 );
ListView1.Location = new Point (208, 40 );
ListView1.Name = "listView1 ";
ListView1.Size = new Size (121,144 );
ListView1.TabIndex = 2;
ListView1.View = View. List;
ListView1.DragDrop + = new DragEventHandler (listviewdomaindragdrop );
ListView1.DragEnter + = new DragEventHandler (listviewdomaindragenter );
ListView1.ItemDrag + = new ItemDragEventHandler (listviewdomainitemdrag );

AutoScaleBaseSize = new Size (6, 14 );
ClientSize = new Size (376,237 );
Controls. Add (listView1 );
Controls. Add (treeView1 );
This. MaximizeBox = false;
This. MinimizeBox = false;
This. Name = "Form1 ";
This. Text = "comprehensive understanding of Drag and Drop Operations in C ";
This. ResumeLayout (false );
}
Static void Main ()
{
Application. Run (new Form1 ());
}
Private void treeviewincluitemdrag (object sender, ItemDragEventArgs e)
{
String strItem = e. Item. ToString ();
// Start the "Drag" Operation
DoDragDrop (strItem, DragDropEffects. Copy | DragDropEffects. Move );
}
Private void listviewincludragenter (object sender, DragEventArgs e)
{
// Determine whether the currently dragged data is a string. If yes, the drag string copies the target component.
If (e. Data. GetDataPresent (DataFormats. Text ))
E. Effect = DragDropEffects. Move;
Else
E. Effect = DragDropEffects. None;
}
Private void listviewincludragdrop (object sender, DragEventArgs e)
{
String dummy = "temp ";
// Obtain the string to be dragged in the Drag operation.
String s = (string) e. Data. GetData (dummy. GetType ());
S = s. Substring (s. IndexOf (":") + 1). Trim ();
Position. X = e. X;
Position. Y = e. Y;
Position = listView1.PointToClient (Position );
// Add a project with the title of this string to the target component
ListView1.Items. Add (new ListViewItem (s, 0 ));
}

Private void listviewincluitemdrag (object sender, ItemDragEventArgs e)
{
// Right-click or press
If (e. Button = MouseButtons. Right) return;
Int nTotalSelected = listView1.SelectedIndices. Count;
// Determine whether a project exists in the component
If (nTotalSelected <= 0) return;
IEnumerator selCol = listView1.SelectedItems. GetEnumerator ();
SelCol. MoveNext ();
ListViewItem lvi = (ListViewItem) selCol. Current;
String mDir = "";
For (int I = 0; I <lvi. SubItems. Count; I ++)
MDir + = lvi. SubItems [I]. Text + ",";
String str = mDir. Substring (0, mDir. Length-1 );
If (str = "") return;
// Drag and drop the string in the component
ListView1.DoDragDrop (str, DragDropEffects. Copy | DragDropEffects. Move );
}
Private void treeviewincludragenter (object sender, DragEventArgs e)
{
// Determine whether the currently dragged data is a string. If yes, the drag string copies the target component.
If (e. Data. GetDataPresent (DataFormats. Text ))
E. Effect = DragDropEffects. Copy;
Else
E. Effect = DragDropEffects. None;
}
Private void treeviewincludragdrop (object sender, DragEventArgs e)
{
// Obtain the string to be dragged in the Drag operation.
String dummy = "temp ";
String s = (string) e. Data. GetData (dummy. GetType ());
S = s. Substring (s. IndexOf (":") + 1). Trim ();
Position. X = e. X;
Position. Y = e. Y;
Position = treeView1.PointToClient (Position );
TreeNode DropNode = this. treeView1.GetNodeAt (Position );
// Add a project with the title of this string to the target component
If (DropNode! = Null)
{
TreeNode DragNode = new TreeNode (s );
TreeView1.Nodes. Insert (DropNode. Index + 1, DragNode );
}
}
}

 

5. Drag and Drop Operations for other components:

This article introduces the drag-and-drop operations between the TreeView component and the ListView component in detail. For other components that can be used for drag-and-drop operations, the implementation of drag-and-drop operations for many components is similar to those of these two methods. However, there are also some differences between some components, such as The ListBox component. During the drag-and-drop operation, there is no "ItemDrag" event described in this article. What should I do. We implement it through a flexible method. Specifically, the "MouseMove" event and "MouseDown" event are used to replace the "ItemDrag" event. The "MouseMove" event mainly serves to trigger the drag-and-drop operation, the "MouseDown" event mainly serves to determine whether the drag-and-drop operation has been completed. The drag-and-drop operations on The ListBox component are similar to the two components described above. The drag-and-drop operations between the ListBox component and other components that do not have the "ItemDrag" event are not described here. I believe you can do this.

6. Summary:

For most components, the solution to the "ItemDrag", "DragEnter", and "DragDrop" events also master the drag-and-drop operations between components. Of course there are some exceptional components, but all in all, the implementation steps of drag-and-drop operations are the same, and the solutions are roughly the same. Due to the advantages of drag-and-drop operations, it is necessary for programmers to master the operation as soon as possible. I hope the content described in this article will satisfy you.

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.