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

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

相关推荐
夜晚中的人海36 分钟前
【C++】二分查找算法习题
开发语言·c++·算法
狮子座的男孩1 小时前
js基础:06、函数(创建函数、参数、返回值、return、立即执行函数、对象(函数))和枚举对象的属性
开发语言·前端·javascript·经验分享·函数·枚举对象·立即执行函数
sulikey2 小时前
【C++ STL 深入解析】insert 与 emplace 的区别与联系(以 multimap 为例)
开发语言·c++·stl·stl容器·insert·emplace
墨白曦煜2 小时前
Java集合框架整体分类(完整的集合框架关系)
java·开发语言
YuanlongWang2 小时前
C# 基础——async/await 的实现原理与最佳实践
开发语言·c#
kkkkk0211062 小时前
JavaScript性能优化实战:深度剖析瓶颈与高效解决方案
开发语言·javascript·性能优化
一碗绿豆汤2 小时前
C语言-结构体
c语言·开发语言
kalvin_y_liu3 小时前
ManySpeech —— 使用 C# 开发人工智能语音应用
开发语言·人工智能·c#·语音识别
bin91533 小时前
AI工具赋能Python开发者:项目开发中的创意守护与效率革命
开发语言·人工智能·python·工具·ai工具