Tech Off Thread

5 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

WinForms question - Preventing focus from being set to a Form

Back to Forum: Tech Off
  • User profile image

    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?

  • User profile image

    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?

  • User profile image

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

  • User profile image

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

  • User profile image

    @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.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.