C#无标题栏窗体拖动

要实现C#无标题栏窗体的拖动功能,可以通过以下步骤实现:

  1. 在窗体的构造函数中添加以下代码,以去掉标题栏:

    this.FormBorderStyle = FormBorderStyle.None;

  2. 然后,添加以下代码以处理鼠标按下事件:

    private const int WM_NCHITTEST = 0x0084;
    private const int HT_CAPTION = 0x0002;

    protected override void WndProc(ref Message m)
    {
    switch (m.Msg)
    {
    case WM_NCHITTEST:
    base.WndProc(ref m);
    if ((int)m.Result == HT_CLIENT)
    m.Result = (IntPtr)HT_CAPTION;
    return;
    }
    base.WndProc(ref m);
    }

  3. 最后,通过处理鼠标按下和移动事件来实现拖动功能:

    private bool isDragging = false;
    private Point lastCursor;
    private Point lastForm;

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
    isDragging = true;
    lastCursor = Cursor.Position;
    lastForm = this.Location;
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
    if (isDragging)
    {
    int x = lastForm.X - (lastCursor.X - Cursor.Position.X);
    int y = lastForm.Y - (lastCursor.Y - Cursor.Position.Y);
    this.Location = new Point(x, y);
    }
    }

    private void Form1_MouseUp(object sender, MouseEventArgs e)
    {
    isDragging = false;
    }

将上述代码添加到你的窗体上即可实现无标题栏窗体的拖动功能。

相关推荐
zh_xuan几秒前
kotlin伴生对象
开发语言·kotlin
你怎么知道我是队长8 分钟前
C语言---递归
c语言·开发语言
superman超哥13 分钟前
实时互动的基石:Rust WebSocket 实现的架构之美
开发语言·rust·编程语言·rust websocket·rust实施互通·rust架构之美
古城小栈13 分钟前
编译型 VS 解释型, 快慢有道
开发语言
qq_3660862218 分钟前
log.info中使用多个占位符{}问题
开发语言
{Hello World}27 分钟前
Java多态:三大条件与实现详解
java·开发语言
老蒋每日coding28 分钟前
Java解析Excel并对特定内容做解析成功与否的颜色标记
java·开发语言·excel
lang2015092828 分钟前
Java反射利器:Apache Commons BeanUtils详解
java·开发语言·apache
沐知全栈开发29 分钟前
HTML DOM 方法
开发语言
扶苏100231 分钟前
前端js高频面试点汇总
开发语言·前端·javascript