當把Winform的FormBorderStyle設置爲None的時候,因爲窗體沒有了標題欄,所以不能夠移動窗體,
而是用如下幾種方法,便可以在此情況下,通過點擊窗體來移動窗體:
一、是用重載WndProc消息的方法:
大概原理是利用原來Windows對鼠標在標題欄上活動(鼠標按下、移動、鼠標擡起)的響應(移動),
即獲取到鼠標在客戶區活動的消息後,改變消息返回,由客戶區改爲標題欄區。
定義常量:
const int WM_NCHITTEST = 0x0084; \\Windows用來獲取鼠標命中在窗體的哪個部分
const int HTCAPTION = 2; //標題欄
const int HTCLIENT = 1; //客戶區
重載方法:
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case WM_NCHITTEST:
if (m.Result == (IntPtr)HTCLIENT)
m.Result = (IntPtr)HTCAPTION;
break;
}
}
相關參考:http://www.cnblogs.com/GnagWang/archive/2010/09/12/1824394.html
二、當MouseDown時,發送移動消息的方法:
定義常量:
public
const
uint
WM_SYSCOMMAND = 0x0112;
public
const
int
SC_MOVE = 61456;
public
const
int
HTCAPTION = 2; \\標題欄
聲明Windows API:
[DllImport(
"User32.DLL"
)]
public
static
extern
bool
ReleaseCapture();
[DllImport(
"User32.DLL"
)]
public
static
extern
int
SendMessage(IntPtr hWnd,
uint
Msg,
int
wParam,
int
lParam);
定義MouseDown事件:
private
void
Form1_MouseDown(
object
sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
}
三、在MouseDown時記錄鼠標位置並修改移動標記爲true,在MouseMove並且移動標記爲true時,根據新鼠標位置和原來鼠標位置進行移動,並
重新記錄新的鼠標位置,在MouseUp時,修改移動標記爲false。
聲明變量:
Point mouse;
bool Capture;
定義事件:
MouseDown(object sender,MouseEventArgs e)
{
mouse=e.Location;
Capture=true;
}
MouseMove(object sender,MouseEventArgs e)
{
if(this.Capture)
{
Point p=Control.MousePosition;
p.Offset(-mouse.X,-mouse.Y)
ctrl.Location=p; (ctrl爲要移動的窗體或者控件)
}
}
MouseUp(object sender,MouseEventArgs e)
{
this.Capture=false;
}