C# Winform 用鼠标拖动工作区

方案1:通过重载消息处理实现。(优点:不用声明api函数。缺点是:窗体上放着Panel等容器就会失效)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
constintWM_NCHITTEST = 0x0084;
constintHTLEFT = 10;
constintHTCAPTION = 2;
constintHTCLIENT = 1;
protectedoverridevoidWndProc(refMessage m)
{
base.WndProc(refm);
switch(m.Msg)
{
caseWM_NCHITTEST:
if(m.Result == (IntPtr)HTCLIENT)
m.Result = (IntPtr)HTCAPTION;
break;
}
}

方案2:发送一个拖动的消息(优点是:可以放在任意控件鼠标按下事件中)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Runtime.InteropServices;

[DllImport("User32.DLL")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("User32.DLL")]
public static extern bool ReleaseCapture();
public const uint WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 61456;
public const int HTCAPTION = 2;

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
}