Вопрос

I have a UserControl-derived control with several sub-controls (here: three docked labels). In order to react on a click anywhere on the UserControl, I override WndProc() and look for

WM_PARENTNOTIFY/WM_LBUTTONCLICK

-- this was suggested on MSDN, and it does work well.

The reaction on the user's mouseclick is to open a (modal) popup dialog. However, when I try to implement this, a strange behaviour shows up: Sometimes, the dialog flickers several times, and a Windows sound occurs. After closing the dialog, the user has to click into the main window (containing the UserControl) to re-set the focus. Sometimes, no flicker and no sound, but the main form loses focus as well.

In contrast to this, the button next to the UserControl also opens that popup dialog. There is no flicker and no sound, and after closing the popup the main window automatically has the focus again.

What's wrong with the UserControl/WndProc construction?

I'm including an example project (VS2008) to illustrate the behaviour: (via DropBox)

Это было полезно?

Решение

Try using BeginInvoke to start the event after the WndProc method has finished:

protected override void WndProc(ref Message m) {
  //0x210 is WM_PARENTNOTIFY
  if (m.Msg == 0x210 && m.WParam.ToInt32() == 513)    //513 is WM_LBUTTONCLICK
    {
    Console.WriteLine("## MouseClick on UserControl1 ");
    this.BeginInvoke(new Action(() => UserControlClicked(this, new EventArgs())));
    return;
  }
  /*
  else if (m.Msg == 0x2a1) // WM_MOUSEHOVER
      TTrace.Debug.Send("## WMsg " + m.Msg + " / WParam " + m.WParam.ToInt32());
  */
  base.WndProc(ref m);
}

Другие советы

This probably happens, because you are opening a form while an event is still being processed. Depending on the timing and/or the position of the timer, the pending click event might be triggered for the main form or for the dialog form.

I suggest a workaround.

After detecting the click, start a timer that opens the dialog form after a short time (50 ms or so). This decouples the click event processing from the form opening. This trick helped me in solving this kind of problem several times.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top