WinForms dialogs with TopMost = true

2019-07-24 04:39发布

I have a dialog implemented in WinForms that is shown as a notify dialog on the bottom right of the screen. The problem is that whenever is shown it takes the focus and this happens only when TopMost = true. How can I solve this?

3条回答
你好瞎i
2楼-- · 2019-07-24 05:09

You need to inherit from Form and override a couple of properties:

[Flags]
enum WS_EX
{
    TOPMOST = 0x00000008,
}

class TopMostForm : Form
{
    protected override CreateParams CreateParams
    {
        get
        {
            var baseParams = base.CreateParams;
            baseParams.ExStyle |= (int)WS_EX.TOPMOST;
            return baseParams;
        }
    }

    protected override bool ShowWithoutActivation
    {
        get { return true; }
    }
}

Then just simply Show() on this form and it will be displayed as topmost and inactive.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-07-24 05:21

Show the dialog with Show instead of ShowDialog. ShowDialog will be topmost, user has to click it before doing something else (modal) Show will show it as normal.

查看更多
Rolldiameter
4楼-- · 2019-07-24 05:25

How about this strategy:

  1. Show it at startup, then immediately:
  2. Hide it with ShowWindow( SW_HIDE )
  3. Never ever close the form, just let it be invisible
  4. Show it with ShowWindow( SW_SHOWNOACTIVATE )
查看更多
登录 后发表回答