Tech Off Thread

5 posts

WinForms question - Preventing focus from being set to a Form

Back to Forum: Tech Off
  • BitFlipper

    I got tired of ToolTip flashing when you update it's location (I want it to follow the mouse pointer), so I decided to create my own tooltip derived from Form. It works well, smooth as butter with no flashing, however I ran into the following problem:

    Whenever the tooltip is showm it takes the focus and the main form loses focus. I can manually set focus back to the main window after showing the tooltip, but there is a noticeable flash as the main form loses/regains focus.

    I'm trying to figure out how to prevent focus to shift to the custom tooltip. I tried setting various properties related to being selectable, enabled etc but nothing works. I also tried SetStyle(ControlStyles.Selectable, false) but that didn't make any difference.

    Any suggestions?

  • BitFlipper

    I found this that would solve my problem. Seems a lot of code just to prevent the focus to change.

    EDIT: Well I tried that and it doesn't work for me. The custom tooltip still gets the focus.

    EDIT EDIT: OK the weird thing is that when I'm using the example code from that link and I override OnActivated and call...

    SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE);

    ...that the breakpoint in OnActivated is hit, showing the SetWindowPos in the call stack. So the SetWindowPos causes the window to become active. Isn't that what the SWP_NOACTIVATE is supposed to prevent?

  • DaveWill2

    An idea:  What about not using a form and instead using a panel with a z-index that gives the same effect.

  • lensman

    Why simply disable the form. It cannot get focus if not enabled. 

  • BitFlipper

    @DaveWill2: The problem with a non-Form panel is that I don't believe it can go out of the bounds of the parent window (or at least it will be clipped). Tooltips can go off the edge of the parent form.

    @ lensman: I tried that but get an exception during the Show call that a Form cannot be displayed if it is disabled.

    In the end I did find a working combination of SetWindowLong(WS_EX_NOACTIVATE), ShowWindow(SW_SHOWNOACTIVATE), overriding Form.ShowWithoutActivation and returning true, and override CreateParams and returning WS_EX_NOACTIVATE.

    Strangely if I leave any of the above out it stops working properly. Like how many times do you need to tell it not to activate? It's working the way I want it to now so I'm just going to leave it as is.

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.