c# 移动窗体和控件
在winform程序里面,有时候我们需要移动没有标题栏窗体或是窗体内的控件,用几个事件如鼠标单击,移动,等再加上坐标的计算可以完成这一功能,但是最近发现了一个API函数,可以非常简单方便的完成这个功能。如下:
代码
[DllImportAttribute("user32.dll")]
private extern static bool ReleaseCapture();
[DllImportAttribute("user32.dll")]
private extern static int SendMessage(IntPtr handle, int m, int p, int h);
private extern static bool ReleaseCapture();
[DllImportAttribute("user32.dll")]
private extern static int SendMessage(IntPtr handle, int m, int p, int h);
在使用这两个函数时就导入using System.Runtime.InteropServices;
如下使用:
ReleaseCapture();
SendMessage(this.Handle, 0xA1, 0x2, 0);
这里面除this.Handle参数外其它的不需改变。例如我们给窗体定义一个MouseDown事件:
this.MouseDown += new MouseEventHandler(MyBaseControl_MouseDown);
那么就可以在点击窗体的任何一点而进行拖动操作。事件内代码如:
代码
1 protected void MyBaseControl_MouseDown(object sender, MouseEventArgs e)
2 {
3 if (e.Button == MouseButtons.Left)
4 {
5 this.Cursor = Cursors.SizeAll;
6 ReleaseCapture();
7 SendMessage(this.Handle, 0xA1, 0x2, 0);
8 this.Cursor = Cursors.Default;
9 }
10 }
11
2 {
3 if (e.Button == MouseButtons.Left)
4 {
5 this.Cursor = Cursors.SizeAll;
6 ReleaseCapture();
7 SendMessage(this.Handle, 0xA1, 0x2, 0);
8 this.Cursor = Cursors.Default;
9 }
10 }
11
如果用于运行时的某个控件,则可以把上面的代码放入此控件的MouseDown事件中,只是SendMessage(this.Handle, 0xA1, 0x2, 0);中的
this.Handle参数应改为此控件的Handle,如this.button1.Handle即可实现。
补充:软件开发 , C# ,