溫馨提示×

winform窗體移動的方法是什么

小億
164
2023-11-13 10:00:49
欄目: 智能運維

在WinForms中,窗體的移動可以通過以下方法實現:

  1. 使用鼠標事件:通過處理鼠標按下、移動和釋放事件來實現窗體的移動??梢栽谑髽税聪率录杏涗浭髽说某跏嘉恢?,并在鼠標移動事件中計算鼠標的偏移量,然后通過修改窗體的位置實現移動效果。
private Point mouseOffset;

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    mouseOffset = new Point(-e.X, -e.Y);
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Point mousePos = Control.MousePosition;
        mousePos.Offset(mouseOffset.X, mouseOffset.Y);
        Location = mousePos;
    }
}
  1. 使用Windows消息:通過重寫窗體的WndProc方法,處理WM_NCHITTEST和WM_NCLBUTTONDOWN消息來實現窗體的移動。WM_NCHITTEST消息用于確定鼠標點擊的位置,WM_NCLBUTTONDOWN消息用于處理鼠標按下事件。
private const int WM_NCHITTEST = 0x0084;
private const int HT_CAPTION = 0x0002;
private const int WM_NCLBUTTONDOWN = 0x00A1;

protected override void WndProc(ref Message m)
{
    switch (m.Msg)
    {
        case WM_NCHITTEST:
            base.WndProc(ref m);
            if (m.Result.ToInt32() == HT_CAPTION)
                m.Result = new IntPtr(HT_CLIENT);
            return;
        case WM_NCLBUTTONDOWN:
            if ((int)m.WParam == HT_CAPTION)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, new IntPtr(HT_CAPTION), IntPtr.Zero);
            }
            break;
    }
    base.WndProc(ref m);
}

以上是兩種常用的方法,可以根據實際需要選擇適合的方法來實現窗體的移動。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女