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

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

相关推荐
tkevinjd1 小时前
C++中线程库的基本操作
开发语言·c++
CodeWithMe1 小时前
【C/C++】不同防止头文件重复包含的措施
c语言·开发语言·c++
子豪-中国机器人1 小时前
C++ 信息学奥赛总复习题答案解析
开发语言·c++·算法
oioihoii2 小时前
C++11列表初始化:从入门到精通
java·开发语言·c++
zdy12635746882 小时前
python第48天打卡
开发语言·python
whoarethenext2 小时前
使用 C++/OpenCV 创建动态流星雨特效 (实时动画)
开发语言·c++·opencv
Mr...Gan2 小时前
TypeScript
开发语言·javascript·typescript
前端 贾公子3 小时前
《Vuejs设计与实现》第 8 章(挂载与更新)
开发语言·前端·javascript
CodeCraft Studio3 小时前
Excel处理控件Aspose.Cells教程:使用 C# 在 Excel 中应用数据验证
c#·excel·aspose·文档开发·文档处理
ღ 噫吁嚱3 小时前
【C/C++】实现固定地址函数调用
c语言·开发语言·c++