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

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

相关推荐
只想摆烂@15 分钟前
C# winfrom 如何多窗体优雅的回调方法
开发语言·c#
西猫雷婶17 分钟前
python画图|中秋到了,尝试画个月亮(球体画法)
开发语言·python
星迹日19 分钟前
C语言:结构体
c语言·开发语言·经验分享·笔记
会敲代码的小张31 分钟前
设计模式-观察者模式
java·开发语言·后端·观察者模式·设计模式·代理模式
宗浩多捞35 分钟前
C++设计模式(更新中)
开发语言·c++·设计模式
学习使我变快乐3 小时前
C++:析构函数
开发语言·c++
锋君3 小时前
C# 手动写入日志,过大写入新文件
c#
我言秋日胜春朝★3 小时前
【C++】继承详解
开发语言·c++
+码农快讯+6 小时前
JavaScript 基础 - 第17天_AJAX综合案例
开发语言·javascript·ajax
计算机学姐7 小时前
基于python+django+vue的二手电子设备交易平台
开发语言·vue.js·后端·python·mysql·django·web3.py