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;
    }

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

相关推荐
weixin_421922691 分钟前
模板代码性能测试
开发语言·c++·算法
Red丶哞6 分钟前
内网自建Postfix使用Python发送邮件
开发语言·python
静心观复9 分钟前
使用 new 关键字和 Java 反射创建对象的区别
java·开发语言
Liu6288813 分钟前
C++中的模板方法模式
开发语言·c++·算法
qq_3349031520 分钟前
高性能网络协议栈
开发语言·c++·算法
阿贵---24 分钟前
模板编译期循环展开
开发语言·c++·算法
2601_9540236624 分钟前
Beyond the Hype: Deconstructing the 2025 High-Performance Stack for Agencies
java·开发语言·算法·seo·wordpress·gpl
l1t28 分钟前
DeepSeek 辅助编写python程序求解欧拉计划932题:2025数
开发语言·python·欧拉计划
2401_8331977331 分钟前
嵌入式C++电源管理
开发语言·c++·算法
ms_27_data_develop34 分钟前
Java——集合
java·开发语言