WindowsForm如何移動一個沒有標題欄的窗口


在WinForm程序中,要移動沒有標題欄的窗口,基本的實現思路是監聽需要拖動窗口內的控件的鼠標事件,然后將鼠標位置發送給窗口進行相應的位移就可以了。通過借用Windows API也可以很容易實現這一點,比如像下面這樣。

public class Win32Api
{
    public const int WM_SYSCOMMAND = 0x112;
    public const int SC_DRAGMOVE = 0xF012;

    [DllImport("user32.Dll", EntryPoint = "ReleaseCapture")]
    public extern static void ReleaseCapture(); // 鼠標捕獲
    [DllImport("user32.Dll", EntryPoint = "SendMessage")]
    public extern static void SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam); // 將消息發送給指定的窗口
}

private void pnlHeader_MouseDown(object sender, MouseEventArgs e)
{
    Win32Api.ReleaseCapture();
    Win32Api.SendMessage(this.Handle, Win32Api.WM_SYSCOMMAND, Win32Api.SC_DRAGMOVE, 0);
}

當然,你還可以向這樣向窗口發送消息,來實現拖動自定義標題欄移動窗口

public const int WM_NCLBUTTONDOWN = 0x00A1;
public const int HTCAPTION = 2;

private void pnlHeader_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        // 釋放控件已捕獲的鼠標
        pnlHeader.Capture = false;

        // 創建並發送WM_NCLBUTTONDOWN消息
        Message msg =
            Message.Create(this.Handle, Win32Api.WM_NCLBUTTONDOWN,
                new IntPtr(Win32Api.HTCAPTION), IntPtr.Zero);
        this.DefWndProc(ref msg);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM