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

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

相关推荐
diegoXie3 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条4 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
liulilittle4 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
失散134 小时前
Python——1 概述
开发语言·python
萧鼎4 小时前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法
小小8程序员5 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++
立志成为大牛的小牛5 小时前
数据结构——五十六、排序的基本概念(王道408)
开发语言·数据结构·程序人生·算法
老王熬夜敲代码5 小时前
C++中的atomic
开发语言·c++·笔记·面试
a努力。5 小时前
腾讯Java面试被问:String、StringBuffer、StringBuilder区别
java·开发语言·后端·面试·职场和发展·架构
长安第一美人5 小时前
php出现zend_mm_heap corrupted 或者Segment fault
开发语言·嵌入式硬件·php·zmq·工业应用开发