Under normal circumstances:
1 1Add the following code to your form:2 #regionEasy to move3 4 BOOLIsinmove;5 Point oldpoint;6 7 voidInitializeeasymove ()8 {9Isinmove =false;Ten One This. MouseDown + =NewMouseEventHandler (easymove_mousedown); A This. MouseUp + =NewMouseEventHandler (easymove_mouseup); - This. MouseMove + =NewMouseEventHandler (easymove_mousemove); - } the - voidEasymove_mousemove (Objectsender, MouseEventArgs e) - { - if(!isinmove)return; +Point pt =Pointtoscreen (e.location); - if(Pt. X = = Oldpoint.x | | Pt. Y = = Oldpoint.y)return; + This. Location =NewPoint ( This. Location.x + Pt. X-oldpoint.x, This. LOCATION.Y + Pt. Yoldpoint.y); AOldpoint =pt; at } - - voidEasymove_mouseup (Objectsender, MouseEventArgs e) - { -Isinmove =false; - } in - voidEasymove_mousedown (Objectsender, MouseEventArgs e) to { +Isinmove =true; -Oldpoint =Pointtoscreen (e.location); the } * $ #endregionPanax Notoginseng - 2called in the constructor or load event of your form: theInitializeeasymove ();
But you will find it troublesome, and the runtime is prone to error.
Improvement One:
increase the MouseLeave event to set the Isinmove to False when MouseLeave
This is a little bit improved, though. But it's a little awkward.
Improvement Two:
Using Win32API
1 Public Partial classForm6:form2 {3[DllImport ("user32.dll")]4 Public Static extern BOOLreleasecapture ();5[DllImport ("user32.dll")]6 Public Static extern BOOLSendMessage (INTPTR hwnd,intWmsg,intWParam,intlParam);7 Public Const intWm_syscommand =0x0112;8 Public Const intSc_move =0xf010;9 Public Const intHtcaption =0x0002;Ten One PublicFORM6 () A { - InitializeComponent (); - } the - Private voidForm6_mousedown (Objectsender, MouseEventArgs e) - { - releasecapture (); +SendMessage ( This. Handle, Wm_syscommand, Sc_move + htcaption,0); - } +}
The amount of code is greatly reduced, which directly eliminates the bug that occurs when the mouse moves quickly. But when the mouse click Pannel,groupbox Wait or no response
Improvement Three:
1 Public Partial classForm1:form2 {3[DllImport ("user32.dll")]4 Public Static extern BOOLreleasecapture ();5[DllImport ("user32.dll")]6 Public Static extern BOOLSendMessage (INTPTR hwnd,intWmsg,intWParam,intlParam);7 Public Const intWm_syscommand =0x0112;8 Public Const intSc_move =0xf010;9 Public Const intHtcaption =0x0002;Ten PublicForm1 () One { A InitializeComponent (); - foreach(varIteminch This. Controls) - { the if(item asGROUPBOX)! =NULL) - { -(item asGroupBox). MouseDown + =Form6_mousedown; - } + Else if(item asPanel)! =NULL) - { +(item asPanel). MouseDown + =Form6_mousedown; A } at } - } - - Private voidForm6_mousedown (Objectsender, MouseEventArgs e) - { - releasecapture (); inSendMessage ( This. Handle, Wm_syscommand, Sc_move + htcaption,0); - } to}
Add MouseDown actions to GroupBox, Pannel, and other controls
OK, you are done.
C # implementing form movement