C#窗体移动实现步骤:(转)
首先建一个Windows应用程序,将Form1的 FormBorderStyle属性设置为Noe
要调用Windows 的API, 必须得引用命名空间: using System.Runtime.InteropServices;
方法一: 不用事件,重写WndProc
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TestFormMove
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
private const int WM_SYSCOMMAND = 0x0112;//点击窗口左上角那个图标时的系统信息
private const int HTCAPTION = 0x0002;//表示鼠标在窗口标题栏时的系统信息
private const int WM_NCHITTEST = 0x84;//鼠标在窗体客户区时发送的消息
private const int HTCLIENT = 0x1;//表示鼠标在窗口客户区的系统消息
private const int SC_MAXIMIZE = 0xF030;//最大化信息
private const int SC_MINIMIZE = 0xF020;//最小化信息
private const int WM_NCLBUTTONDBLCLK = 0xA3;//窗体双击
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_NCLBUTTONDBLCLK://无标题窗口双击禁止最大化
return;
case WM_SYSCOMMAND:
if (m.WParam == (IntPtr)SC_MAXIMIZE)
{
m.WParam = (IntPtr)SC_MINIMIZE;
}
break;
case WM_NCHITTEST: //如果鼠标移动或单击
base.WndProc(ref m);//调用基类的窗口过程——WndProc方法处理这个消息
if (m.Result == (IntPtr)HTCLIENT)//如果返回的是HTCLIENT
{
m.Result = (IntPtr)HTCAPTION;//把它改为HTCAPTION
return;//直接返回退出方法
}
break;
}
base.WndProc(ref m);//如果不是鼠标移动或单击消息就调用基类的窗口过程进行处理
}
}
}
方法二: 为窗体添加鼠标MouseDown 事件即可
[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;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}