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

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

相关推荐
加号314 小时前
【C#】 字符串字节到十六进制字节数组的转换解析
c#
吃好睡好便好14 小时前
用while循环语句求和
开发语言·学习·算法·matlab·信息可视化
TechWayfarer14 小时前
查询IP所在地的3种方案:从API到离线库,风控场景怎么选?
开发语言·网络·python·网络协议·tcp/ip
摇滚侠14 小时前
Java 零基础全套教程,集合框架,笔记 153-163
java·开发语言·笔记
程序员榴莲14 小时前
Python 单例模式
开发语言·python·单例模式
L、21815 小时前
CANN算子开发调试实战:从“Segmentation Fault“到定位根因的完整流程
java·开发语言
JaydenAI15 小时前
[MAF的Agent管道详解-04]如何让LLM按照要求的结构输出数据?
ai·c#·agent·maf·agent pipeline
狗凯之家源码网15 小时前
基于PHP的多语言跨境电商B2B2C商城系统技术解析
开发语言·php
比特森林探险记16 小时前
go 语言中的context 解读和用法
开发语言·后端·golang
古城小栈16 小时前
Rust 调用 C 语言库 实战指南(企业级)
c语言·开发语言·rust