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

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

相关推荐
一轮弯弯的明月11 分钟前
Python基础-速通秘籍(下)
开发语言·笔记·python·学习
西西学代码20 分钟前
Flutter---回调函数
开发语言·javascript·flutter
大尚来也31 分钟前
深入HashMap底层:从JDK1.7到1.8的架构演进与性能突围
开发语言
森林里的程序猿猿1 小时前
并发设计模式
java·开发语言·jvm
222you1 小时前
四个主要的函数式接口
java·开发语言
smchaopiao3 小时前
Python中字典与列表合并的问题与解决方法
开发语言·python
敲代码的瓦龙3 小时前
Java?面向对象三大特性!!!
java·开发语言
2501_921649493 小时前
期货 Tick 级数据与基金净值历史数据 API 接口详解
开发语言·后端·python·websocket·金融·区块链
野犬寒鸦3 小时前
Redis复习记录day1
服务器·开发语言·数据库·redis·缓存