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

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

相关推荐
光泽雨4 小时前
C# 中 Assembly 类详解
开发语言·c#
少控科技4 小时前
C#基础训练营 - 02 - 运算器
开发语言·c#
Riemann~~5 小时前
C语言嵌入式风格
c语言·开发语言
zmzb01037 小时前
C++课后习题训练记录Day104
开发语言·c++
zmzb01037 小时前
C++课后习题训练记录Day105
开发语言·c++·算法
wjs20247 小时前
Vue3 条件语句
开发语言
_codemonster8 小时前
JavaWeb开发系列(六)JSP基础
java·开发语言
Web打印8 小时前
Phpask(php集成环境)之16 怎样彻底停用一个网站
开发语言·php
临水逸8 小时前
飞牛fnos 2025 漏洞Java跨域URL浏览器
java·开发语言·安全·web安全
H Corey8 小时前
数据结构与算法:高效编程的核心
java·开发语言·数据结构·算法