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

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

相关推荐
Hx_Ma1637 分钟前
SpringMVC框架提供的转发和重定向
java·开发语言·servlet
期待のcode1 小时前
原子操作类LongAdder
java·开发语言
A_nanda2 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
lly2024062 小时前
C 语言中的结构体
开发语言
JAVA+C语言3 小时前
如何优化 Java 多主机通信的性能?
java·开发语言·php
青岑CTF4 小时前
攻防世界-Ics-05-胎教版wp
开发语言·安全·web安全·网络安全·php
Li emily4 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
码云数智-园园4 小时前
使用 C# 将 PowerPoint 演示文稿高效转换为 PDF 格式
c#
APIshop4 小时前
Java 实战:调用 item_search_tmall 按关键词搜索天猫商品
java·开发语言·数据库
血小板要健康4 小时前
Java基础常见面试题复习合集1
java·开发语言·经验分享·笔记·面试·学习方法