Reputation: 644
I'm looking for a way to move the form by using a menustrip.
Although there are a few solutions around, there is a particular problem with them which I don't like. In order for those methods to work the form needs to be already focused before dragging the menustrip.
Is there a way of fixing that particular issue so the menustrip will actually behave like a proper windows title bar ?
Upvotes: 4
Views: 1994
Reputation: 5310
The best bet is to use pinvoke. Tie the "mousedown" event to which ever control you want to be dragable.
using System.Runtime.InteropServices;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
private static extern int SendMessage(IntPtr hWnd,
int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
private static extern bool ReleaseCapture();
public Form1()
{
InitializeComponent();
}
private void menuStrip1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
This still require the form to be focused, but you can work around using mouse hover. It is not that elegant but it works.
private void menuStrip1_MouseHover(object sender, EventArgs e)
{
Focus();
}
Update: Hover has a slight delay, mousemove is much more responsive
private void menuStrip1_MouseMove(object sender, MouseEventArgs e)
{
if (!Focused)
{
Focus();
}
}
Upvotes: 4