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

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

相关推荐
笨笨马甲15 分钟前
Qt Quick模块功能及架构
开发语言·qt
夜晚回家30 分钟前
「Java基本语法」代码格式与注释规范
java·开发语言
YYDS31434 分钟前
C++动态规划-01背包
开发语言·c++·动态规划
安木夕37 分钟前
C#-Visual Studio宇宙第一IDE使用实践
前端·c#·.net
前端页面仔43 分钟前
易语言是什么?易语言能做什么?
开发语言·安全
树叶@1 小时前
Python数据分析7
开发语言·python
wydaicls1 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
Biomamba生信基地2 小时前
R语言基础| 下载、安装
开发语言·r语言·生信·医药
姜君竹2 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构
奇树谦2 小时前
使用VTK还是OpenGL集成到qt程序里哪个好?
开发语言·qt