语言c#,代码来自网上。
第一种,处理mousedown,mouseup,mousemove,mousedown时设置条件量,在mousemove中改变窗口位置。
局部成员声明。
private Point ptMouseCurrrnetPos, ptMouseNewPos,
ptFormPos, ptFormNewPos;
private bool blnMouseDown=false;
主要的三个鼠标事件,即MouseDown、 MouseMove、 MouseUp三个事件。
private void frmTopMost_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if( blnMouseDown )
{
//Get the current position of the mouse in the screen
ptMouseNewPos = Control.MousePosition;
//Set window position
ptFormNewPos.X = ptMouseNewPos.X - ptMouseCurrrnetPos.X + ptFormPos.X;
ptFormNewPos.Y = ptMouseNewPos.Y - ptMouseCurrrnetPos.Y + ptFormPos.Y;
//Save window position
Location = ptFormNewPos;
ptFormPos = ptFormNewPos;
//Save mouse position
ptMouseCurrrnetPos = ptMouseNewPos;
}
}
private void frmTopMost_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button==MouseButtons.Left)
{
blnMouseDown = true;
// Save window position and mouse position
ptMouseCurrrnetPos = Control.MousePosition;
ptFormPos = Location;
}
}
private void frmTopMost_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if( e.Button == MouseButtons.Left)
//Return back signal
blnMouseDown = false;
}
这个方法对程序其他逻辑部分影响最小。
第二种,将客户区的鼠标事件映射到标题栏。
const int WM_NCHITTEST = 0x0084;
const int HTCLIENT = 0x0001;
const int HTCAPTION = 0x0002;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
switch(m.Msg)
{
case WM_NCHITTEST:
base.WndProc(ref m);
if (m.Result==(IntPtr)HTCLIENT)
m.Result=(IntPtr)HTCAPTION;
break;
default:
base.WndProc(ref m);
break;
}
}
const int HTCLIENT = 0x0001;
const int HTCAPTION = 0x0002;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
switch(m.Msg)
{
case WM_NCHITTEST:
base.WndProc(ref m);
if (m.Result==(IntPtr)HTCLIENT)
m.Result=(IntPtr)HTCAPTION;
break;
default:
base.WndProc(ref m);
break;
}
}
因为是把客户区的鼠标时间映射到了标题栏,所以本来正常的客户区鼠标事件如双击等等会被影响。
第三种,发送移动消息。
DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd,int wMsg,int wParam,int lParam);
public const int WM_SYSCOMMAND=0x0112;
public const int SC_MOVE=0xF010;
public const int HTCAPTION=0x0002;
private void Form2_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle,WM_SYSCOMMAND,SC_MOVE+HTCAPTION, 0);
}
这种方法与第二种类似,左键的双击会被屏蔽。