C#Winform按键处理,以及窗体无边框时的移动
一、处理命令键:
///<Summary>
/// 处理命令键
///</Summary>
/// <param name="msg">win32消息</param>
/// <param name="key">对应的按键</param>
///<result>处理的结构</result>
protected override bool ProcessCmdKey(ref System.Windows.Form.Message msg,System.Windows.From.Key key)
{
switch (key)
{
case Keys.Escape:
this.Close();//esc关闭窗体
return true;
//以下则是实现改键
case Keys.Up:
System.Windows.Forms.SendKeys.Send("{w}");
return true;
case Keys.Down:
System.Windows.Forms.SendKeys.Send("{s}");
return true;
case Keys.Left:
System.Windows.Forms.SendKeys.Send("{a}");
return true;
case Keys.Right:
System.Windows.Forms.SendKeys.Send("{d}");
return true;
case Keys.Enter:
System.Windows.Forms.SendKeys.Send("{tab}");
return true;
}
return base.ProcessCmdKey(ref msg, keyData); //其它的按默认处理
}
二、无边框窗体移动处理
#region 窗体随标题Panel的按下移动而移动
[DllImport("user32.dll")]
public static extern bool ReleaseCapture(); //释放鼠标捕获,恢复正常的输入处理
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); //发送消息至窗体处理 (与PostMessage发送至消息队列不同)
public const int WM_SYSCOMMAND = 0x0112; //点击窗体左上角的图标的系统消息
public const int SC_MOVE = 0xF010; //移动消息
public const int HTCAPTION = 0x0002; //鼠标在标题栏的系统消息
private Point _mouseOffset;//鼠标在控件上的偏移位置
private bool _leftDownFlag;//标签是否为左键
private void panTital_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_mouseOffset=new Point(-e.X,-e.Y);
_leftDownFlag = true;
}
}
private void panTital_MouseMove(object sender, MouseEventArgs e)
{
if (_leftDownFlag)
{
Point moustPoint = Control.MousePosition;
moustPoint.Offset(_mouseOffset.X,_mouseOffset.Y);
((Panel)sender).Parent.Location = moustPoint;
}
}
private void panTital_MouseUp(object sender, MouseEventArgs e)
{
_leftDownFlag = false;
}
private void FrmResult_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
//------------------------end 无边框窗体拖动-----------------------------------
#endregion
涉及的一些事件挂接(窗体挂接的鼠标按下事件略):


浙公网安备 33010602011771号