4

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 ?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
denied66
  • 644
  • 7
  • 18
  • is this Winforms? and can you list the other solutions so we can have a look, thanks – Jeremy Thompson Mar 30 '12 at 02:15
  • As the title says, yes it's winforms :) The method that I'm using at the moment is similar to the one found at http://stackoverflow.com/questions/1592876/c-sharp-make-a-borderless-form-movable – denied66 Mar 30 '12 at 02:26
  • 1
    Please don't prefix your titles with "Winforms: " and such. That's what the tags are for. – John Saunders Mar 30 '12 at 03:57

1 Answers1

4

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();
    }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Du D.
  • 5,062
  • 2
  • 29
  • 34
  • Adding the MouseHover event did the job, thanks. Seems to be firing a bit slow though, so if you quickly try to drag the window it might not work. The MouseEnter event seems that it's not suffering from this issue. – denied66 Mar 30 '12 at 02:56
  • MouseMove is much faster than mousehover, try it out. – Du D. Mar 30 '12 at 03:23
  • MouseMove fires a lot of times though, and considering that the user's mouse might just happen to be passing by the menustrip that will be an issue. MouseEnter seems to be triggering fast enough (I don't seem to have any issue with it so far) and it only gets triggered once. Also negates the need for the if statement since the overhead is minimal. – denied66 Mar 30 '12 at 03:36