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

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

相关推荐
老歌老听老掉牙2 分钟前
PyQt5中RadioButton互斥选择的实现方法
开发语言·python·qt
一路往蓝-Anbo5 分钟前
C语言从句柄到对象 (四) —— 接口抽象:从 Switch-Case 到通用接口
c语言·开发语言·stm32·嵌入式硬件
钰fly5 分钟前
Windows Forms开发工具与功能总结表
前端·c#
csbysj20205 分钟前
WebPages 数据库:构建现代网页管理的基石
开发语言
lzhdim7 分钟前
C#性能优化:从入门到入土!这10个隐藏技巧让你的代码快如闪电
开发语言·性能优化·c#
沐知全栈开发8 分钟前
C 标准库 - `<stdarg.h>`
开发语言
两个人的幸福online9 分钟前
给cocos 3.8 消息控制器
开发语言·javascript·ecmascript
廋到被风吹走10 分钟前
【JAVA】【JDK】java8版本之后各个版本调整
java·开发语言
悟能不能悟18 分钟前
如何处理java.time包类序列化问题,跨版本反序列化 Class对象可能抛出 InvalidClassException
java·开发语言
xxxxxxllllllshi18 分钟前
深入解析单例模式:从原理到实战,掌握Java面试高频考点
java·开发语言·单例模式·面试