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

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

相关推荐
大尚来也12 分钟前
PHP 反序列化漏洞深度解析:从原理利用到 allowed_classes 防御实战
android·开发语言·php
WarrenMondeville14 分钟前
1.Unity面向对象-单一职责原则
unity·设计模式·c#
雕刻刀14 分钟前
ERROR: Failed to build ‘natten‘ when getting requirements to build wheel
开发语言·python
qq_4160187215 分钟前
高性能密码学库
开发语言·c++·算法
小碗羊肉24 分钟前
【从零开始学Java | 第十八篇】BigInteger
java·开发语言·新手入门
宵时待雨26 分钟前
C++笔记归纳14:AVL树
开发语言·数据结构·c++·笔记·算法
执笔画流年呀40 分钟前
PriorityQueue(堆)续集
java·开发语言
山川行43 分钟前
关于《项目C语言》专栏的总结
c语言·开发语言·数据结构·vscode·python·算法·visual studio code
呜喵王阿尔萨斯1 小时前
C and C++ code
c语言·开发语言·c++
左左右右左右摇晃1 小时前
JDK 1.7 ConcurrentHashMap——分段锁
java·开发语言·笔记