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

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

相关推荐
t***5448 小时前
Clang 编译器在 Orwell Dev-C++ 中的局限性
开发语言·c++
oy_mail9 小时前
QoS质量配置
开发语言·智能路由器·php
oyzz1209 小时前
PHP操作redis
开发语言·redis·php
nashane9 小时前
HarmonyOS 6学习:网络能力变化监听与智能提示——告别流量偷跑,打造贴心网络感知应用
开发语言·php·harmony app
凌波粒10 小时前
Java 8 “新”特性详解:Lambda、函数式接口、Stream、Optional 与方法引用
java·开发语言·idea
拾贰_C10 小时前
【Google | Gemini | API | POST】怎么使用Google 的Gemini API (原生版)
开发语言·lua
t***54411 小时前
如何在Dev-C++中选择Clang编译器
开发语言·c++
橙子1991101611 小时前
Java 基础相关
java·开发语言
星越华夏12 小时前
python——三角函数用法
开发语言·python