C#无边框窗体移动的三种方法

Posted GarsonZhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#无边框窗体移动的三种方法相关的知识,希望对你有一定的参考价值。

1. 重写WndProc

技术分享
protected override void WndProc(ref Message m)
{       
        const int WM_NCHITTEST = 0x84;
        const int HTCLIENT = 0x01;
        const int HTCAPTION = 0x02;
         if (m.Msg == WM_NCHITTEST)
        {
                this.DefWndProc(ref m);
                if (m.Result.ToInt32() == HTCLIENT)
                    m.Result = new IntPtr(HTCAPTION);
                else
                    base.WndProc(ref m);
        }
        else
        {
                base.WndProc(ref m);
        }
}
View Code

 

2.创建消息

技术分享
private const int WM_NCLBUTTONDOWN = 0x00A1;
private const int WM_NCHITTEST = 0x84;
private const int HT_CAPTION = 0x2;
private const int HT_CLIENT = 0x1;

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    //this.Capture = false;
    pictureBox1.Capture = false;
    Message msg = Message.Create(Handle, WM_NCLBUTTONDOWN, (IntPtr)HT_CAPTION, IntPtr.Zero);
    WndProc(ref   msg);   
} 
View Code

 

3.调用API代码

技术分享
using System.Runtime.InteropServices;

[DllImport("user32.dll")]
 public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
   public const int WM_SYSCOMMAND = 0x0112;
   public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;


   //在窗体的_MouseDown中加入如下代码:
如:
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
View Code

 

以上是关于C#无边框窗体移动的三种方法的主要内容,如果未能解决你的问题,请参考以下文章

WPF无边框窗体怎么移动?C#

C# winform鼠标移动到窗口给窗口加边框并获得句柄

无边框窗体和用户控件以及权限

C#WinForm无边框窗体移动----模仿鼠标单击标题栏移动窗体位置

C#中去掉winform边框如何拖动

Qt:移动无边框窗体(使用Windows的SendMessage)