WinForms window drag event

2019-09-10 04:03发布

Is there an event in WinForms that get's fired when a window is dragged?

Or is there a better way of doing what I want: to drop the window opacity to 80% when the window is being dragged around?

Unfortunately this is stupidly tricky to search for because everyone is looking for drag and drop from the shell, or some other object.

2条回答
Juvenile、少年°
2楼-- · 2019-09-10 04:45

It's the LocationChanged event you want:

private void YourApp_LocationChanged(object sender, EventArgs e)
{
    this.Opacity = 0.8;
}

You'll have to override WndProc and handle the exit move event to reset the opacity back to 1:

protected override void WndProc(ref Message m)
{
    Trace.WriteLine(m.ToString());
    switch (m.Msg)
    {
        case WMEXITSIZEMOVE:
            this.Opacity = 1.0;
            break;
    }
    base.WndProc(ref m);
}

Not forgetting to define the message code:

private const int WMEXITSIZEMOVE = 0x0232;

It might be more efficient to handle the WM_ENTERSIZEMOVE (code 0x0231) message instead of LocationChanged as this would only result in setting the opacity once (at the start of the drag) rather than continually throughout the drag.

查看更多
男人必须洒脱
3楼-- · 2019-09-10 05:03

No need for WndProc hacking, this works fine:

protected override void OnResizeBegin(EventArgs e) {
  this.Opacity = 0.6;
}
protected override void OnResizeEnd(EventArgs e) {
  this.Opacity = 1.0;
}

Moves also trigger the OnResizeXxx events.

查看更多
登录 后发表回答