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

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

相关推荐
小尧嵌入式几秒前
STM32中OTA介绍及使用
开发语言·stm32·单片机·嵌入式硬件
xincan08181 分钟前
MacOS安装Java+mvn+mvnd+jenv多环境丝滑切换
java·开发语言·macos
我不是程序猿儿3 分钟前
【C#】软件设计,华为的IPD学习之需求开发心得
学习·华为·c#
派大鑫wink3 分钟前
【Day13】集合框架(一):List 接口(ArrayList vs LinkedList)实战
java·开发语言·windows
@小张在努力12 分钟前
Javascript中的闭包
开发语言·javascript·ecmascript
muyouking1113 分钟前
Rust Nightly 切换指南:解锁前沿特性的钥匙
开发语言·后端·rust
辛-夷14 分钟前
js中如何改变this指向
开发语言·前端·javascript
cnnews20 分钟前
用OpenCV实现烟花动画
开发语言·python·opencv·pygame·cv2
Rabi'21 分钟前
Windows系统 Qt 整合 OpenCV4.12.0
开发语言·windows·qt·opencv
88号技师22 分钟前
2025年10月一区SCI-中心碰撞优化算法Centered Collision Optimizer-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法