我正在制作一个自定义的FormBorderStyle
,我希望能够像普通窗口一样调整它的大小。我已经实现了一些代码,但它只有在Form
清除其他控件时才有效。
private void Form1_MouseMove(object sender, EventArgs e)
{
if (e.Location.X < 5 || e.location.X > Width - 5)
{
// Do something
}
}
如何创建全局MouseDown
事件?
你想移动一个没有标题栏的窗口,所以你必须将所需的DLL加载到项目中。ReleaseCapture
:从当前文档中的对象中移除鼠标捕获,SendMessage
:将指定的消息发送到一个或多个窗口。它调用指定窗口的窗口过程,直到窗口过程处理完消息才返回。
您可以使用以下代码使用MouseDown事件移动表单:
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool ReleaseCapture();
private void MouseDownEvent(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
请记住,您可以将MouseDownEvent添加到窗体上的任何控件。例如,如果您在表单上有一个标签,您也可以将MouseDownEvent()
添加到标签的MouseDown
事件中
您可以在InitializeComponent()
方法中看到,我将MouseDownEvent
添加到Form1
和lable1
中:
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.MouseDown += new
System.Windows.Forms.MouseEventHandler(this.MouseDownEvent);
//
// Form1
//
this.MouseDown += new
System.Windows.Forms.MouseEventHandler(this.MouseDownEvent);
}