我有一个没有边框,标题栏,菜单等的Windows窗体。我希望用户能够按住CTRL键,在窗体上的任意位置单击鼠标左键并将其拖动并移动。任何想法如何做到这一点?我试过了,但是闪烁很多:
private void HiddenForm_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
this.SuspendLayout();
Point xy = new Point(this.Location.X + (e.X - this.Location.X), this.Location.Y + (e.Y - this.Location.Y));
this.Location = xy;
this.ResumeLayout(true);
}
}
Run Code Online (Sandbox Code Playgroud)
尝试这个
using System.Runtime.InteropServices;
const int HT_CAPTION = 0x2;
const int WM_NCLBUTTONDOWN = 0xA1;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd,int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
Run Code Online (Sandbox Code Playgroud)
更新资料
的ReleaseCapture()函数释放从在当前线程和恢复正常的鼠标输入的处理的窗口的鼠标捕获。捕获光标的窗口将接收所有鼠标输入,而与光标的位置无关,除非在光标热点位于另一个线程的窗口中时单击鼠标按钮。
在窗口的非客户区域上单击鼠标左键时,将向窗口发送WM_NCLBUTTONDOWN消息。wParam指定命中测试枚举值。我们传递HTCAPTION,并且lParam指定光标位置,我们将其传递为0,以便确保它在标题栏中。