C # Drag and Drop files and open files
Two ListBox events that need to be known: when you drag an object within the control's boundaryDragenterEvent.
Determines whether the object to be dragged is the object you want to put on the control. You need to handle this event when dragging one or more files to the control. This causes
When you drag an object to the top of the control, the corresponding icon can be displayed based on the dragged object. When the dragged object is released to the control
DragdropEvent.
Function Description: drag a file to ListBox. ListBox displays the path of the file, click the path, and click open to open the file.
CodeImplementation:
You need to change the allowdrop attribute of ListBox to true and implement itsDragenter,DragdropThese two events.
Using System; Using System. Collections. Generic; Using System. componentmodel; Using System. Data; Using System. drawing; Using System. LINQ; Using System. text; Using System. Windows. forms; Namespace Dragdrop { Public Partial Class Dragdrop: FORM { Public String Filepath; Public Dragdrop () {initializecomponent ();} /// <Summary> /// Obtain the value of ListBox. /// </Summary> /// <Returns> </returns> Public String Getlistboxitem (){ String Filepath = String . Empty; Bool Isselected = Islistboxselected (); If (Isselected = True ){ String Listboxitemvalue = Lbfilepath. selecteditem. tostring (); filepath = Listboxitemvalue ;} Else {MessageBox. Show ( " ListBox must be selected. " );} Return Filepath ;} /// <Summary> /// Whether the value in The ListBox is selected. /// </Summary> /// <Returns> </returns> Public Bool Islistboxselected (){ Bool Selected; If (Lbfilepath. selectedindex =- 1 ) // When selectedindex =-1, it indicates that no item is selected. {Selected = False ;} Else {Selected = True ;} Return Selected ;} Private Void Lbfilepath_dragenter ( Object Sender, drageventargs e ){ If (E. Data. getdatapresent (dataformats. filedrop) {e. Effect = Dragdropeffects. All ;} Else {E. Effect = Dragdropeffects. None ;}} Private Void Lbfilepath_dragdrop ( Object Sender, drageventargs e ){ String [] S = ( String []) E. Data. getdata (dataformats. filedrop, False ); For ( Int I = 0 ; I <S. length; I ++ ) {Lbfilepath. Items. Add (s [I]) ;}} Private Void Btnopenfile_click ( Object Sender, eventargs e ){ String Filepath = Getlistboxitem (); If (! String . Isnullorempty (filepath) {system. Diagnostics. process. Start (filepath );}}}}
Summary:
DataObjectGetdataMethod returns a string array that containsList boxThe complete path name of the file in the control. You can use the file path information to perform any operations on the file.