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

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

相关推荐
Touper.22 分钟前
JavaSE -- 泛型详细介绍
java·开发语言·算法
sun00770024 分钟前
std::forward作用
开发语言·c++·算法
一名用户1 小时前
unity实现梦日记式传送组件
后端·c#·unity3d
Zhen (Evan) Wang1 小时前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
虾球xz1 小时前
CppCon 2018 学习:THE MOST VALUABLE VALUES
开发语言·c++·学习
阿蒙Amon2 小时前
C#扩展方法全解析:给现有类型插上翅膀的魔法
开发语言·c#
尘浮7282 小时前
60天python训练计划----day59
开发语言·python
Chef_Chen3 小时前
从0开始学习R语言--Day39--Spearman 秩相关
开发语言·学习·r语言
不学会Ⅳ3 小时前
Mac M芯片搭建jdk源码环境(jdk24)
java·开发语言·macos
好开心啊没烦恼4 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas