我有一种情况,我希望通过在其客户区域上按住鼠标右键来移动窗体;正如我所说,这种形式是无国界的。
我想“本地”移动它(如果可能的话,否则其他答案也可以)。我的意思是当你在标题栏上按住鼠标左键时它的行为方式(使用鼠标移动和类似的东西,我得到很多奇怪的行为,但也许只是我)。
我已经阅读了很多内容,这篇文章看起来很有帮助
我尝试了各种方式来使用它并通过http://msdn.microsoft.com/en-us/library/ff468877%28v=VS.85%29.aspx观察其他有用的东西并且WM_NCRBUTTONDOWN出现在我的脑海中,但是wndproc没有检测到它,可能是因为它是由表单处理的?
感谢任何建议,谢谢
弗朗西斯
答案 0 :(得分:5)
public partial class DragForm : Form
{
// Offset from upper left of form where mouse grabbed
private Size? _mouseGrabOffset;
public DragForm()
{
InitializeComponent();
}
protected override void OnMouseDown(MouseEventArgs e)
{
if( e.Button == System.Windows.Forms.MouseButtons.Right )
_mouseGrabOffset = new Size(e.Location);
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
_mouseGrabOffset = null;
base.OnMouseUp(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (_mouseGrabOffset.HasValue)
{
this.Location = Cursor.Position - _mouseGrabOffset.Value;
}
base.OnMouseMove(e);
}
}
答案 1 :(得分:1)
你需要两个P / Invoke方法来完成这个任务。
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hwnd, int msg, int wparam, int lparam);
[DllImport("user32.dll")]
static extern bool ReleaseCapture();
一些常数:
const int WmNcLButtonDown = 0xA1;
const int HtCaption= 2;
处理表单上的MouseDown
事件,然后执行以下操作:
private void Form_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ReleaseCapture();
SendMessage(this.Handle, WmNcLButtonDown, HtCaption, 0);
}
}
这将向您的表单发送与鼠标单击并按住标题区域时收到的相同的事件。移动鼠标,窗口移动。松开鼠标按钮时,移动停止。很容易。