C#中移動無邊框窗體的方法

1.使用WIN32API,該方法模擬了一個左鍵拖動當(dāng)前窗口標(biāo)題欄的消息,僅對使用鼠標(biāo)左鍵拖動窗口有效。由于調(diào)用了ReleaseCapture()函數(shù),窗體原本的鼠標(biāo)事件都無法得到響應(yīng)。

public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();

private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{     
        ReleaseCapture();
        SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}

2.在OnMouseMove事件中實時設(shè)置窗體位置,該方法對左右鍵都有效,切不影響對其他鼠標(biāo)事件的響應(yīng)。

public partial class DragForm : Form
{
    // Offset from upper left of form where mouse grabbed
    private Size? _mouseGrabOffset;

    public DragForm()
    {
        InitializeComponent();
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        if( e.Button == System.Windows.Forms.MouseButtons.Right )
            _mouseGrabOffset = new Size(e.Location);

        base.OnMouseDown(e);
    }

    protected override void OnMouseUp(MouseEventArgs e)
    {
        _mouseGrabOffset = null;

        base.OnMouseUp(e);
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if (_mouseGrabOffset.HasValue)
        {
            this.Location = Cursor.Position - _mouseGrabOffset.Value;
        }

        base.OnMouseMove(e);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容