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

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

相关推荐
封奚泽优2 分钟前
使用Labelme进行图像标注
开发语言·python·labelme
wjs20246 分钟前
C 标准库 - <ctype.h>
开发语言
wjs20248 分钟前
AngularJS与SQL的集成使用指南
开发语言
七号练习生.c36 分钟前
JavaScript基础入门
开发语言·javascript·ecmascript
oioihoii36 分钟前
智能体颠覆教育行业:现状、应用与未来展望调研报告
开发语言
常常不爱学习37 分钟前
Vue3 + TypeScript学习
开发语言·css·学习·typescript·html
No0d1es1 小时前
2025年 CSP-J1 入门级初赛 C++真题
开发语言·c++·青少年编程·csp·信息学奥赛·初赛
Halo_tjn1 小时前
基于 Object 类及包装类的专项实验
java·开发语言·计算机
拾忆,想起1 小时前
超时重传 vs 快速重传:TCP双保险如何拯救网络丢包?
java·开发语言·网络·数据库·网络协议·tcp/ip·php
@老蝴1 小时前
Java EE - 线程的状态
开发语言·java-ee·intellij-idea