问题
I have a situation where I would like to move a windows form by holding right mouse button on it's client area; the form it's borderless as i've stated.
I would like to move it "natively" (if possible, otherwise other answers are ok too). I mean the way it behaves when you hold left mouse button on the titlebar (with mouse-move and things like that I get a lot of strange behaviours, but maybe it's just me).
I've read around a lot of things and this post looks helpful
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/b9985b19-cab5-4fba-9dc5-f323d0d37e2f/
I tried various way to use that and watched through http://msdn.microsoft.com/en-us/library/ff468877%28v=VS.85%29.aspx to find other useful things and WM_NCRBUTTONDOWN came in my mind, however the wndproc doesn't detect it, maybe because it's handled by the form?
Any suggestion are appreciated, thanks
Francesco
回答1:
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);
}
}
回答2:
You need two P/Invoke methods to get this done.
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hwnd, int msg, int wparam, int lparam);
[DllImport("user32.dll")]
static extern bool ReleaseCapture();
A couple of constants:
const int WmNcLButtonDown = 0xA1;
const int HtCaption= 2;
Handle the MouseDown
event on your form, then do this:
private void Form_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ReleaseCapture();
SendMessage(this.Handle, WmNcLButtonDown, HtCaption, 0);
}
}
This will send your form the same event it receives when the mouse clicks and holds down the caption area. Move the mouse and the window moves. When you release the mouse button, movement stops. Very easy.
来源:https://stackoverflow.com/questions/5827208/move-a-borderless-winform-holding-right-mouse-button-possibly-with-native-metho