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

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

相关推荐
sycmancia2 分钟前
Qt——对话框及其类型
开发语言·qt
趙卋傑7 分钟前
测试开发场景下常见的 MCP 服务
开发语言·python·测试工具·ai编程
@atweiwei8 分钟前
langchainrust:Rust 版 LangChain 框架(LLM+Agent+RAG)
开发语言·rust·langchain·agent·向量数据库·rag
阿里嘎多学长10 分钟前
2026-04-11 GitHub 热点项目精选
开发语言·程序员·github·代码托管
yugi98783810 分钟前
基于最大信息熵的粒子群优化算法图像分割(MATLAB实现)
开发语言·算法·matlab
yaoxin52112310 分钟前
376. Java IO API - 使用 Globbing 和自定义 Filter 过滤目录内容
java·开发语言·python
飞翔的SA19 分钟前
全程 Python:无需离开 Python 即可实现光速级 CUDA 加速,无需c++支持
开发语言·c++·python·nvidia·cuda
冰暮流星26 分钟前
javascript之dom访问css
开发语言·javascript·css
北风toto26 分钟前
java进制转换方法
java·开发语言·python
楼田莉子33 分钟前
设计模式:创建型设计模式简介
服务器·开发语言·c++·设计模式