Enable/Disable activation of a Form

2019-06-13 16:11发布

问题:

I want to disable a Form from being activated. To do that I use this:

private const int WS_EX_NOACTIVATE = 0x08000000;
protected override CreateParams CreateParams
{
   get
      {
          CreateParams createParams = base.CreateParams;
          createParams.ExStyle = WS_EX_NOACTIVATE;
          return createParams;
       }
}

This is fine for the main activity of my program because I can still click on the buttons and the Form won't activate. Whatever program is in the foreground stays there.

The problem is at the beginning of my program I need to input some text with the keyboard and for that the Form must be active or else the text will go to the program in the foreground.

I know where and when I want to enable/disable the Form ability to be activated, I just don't know how.

EDIT: And when it's not able to be active anymore I still want the buttons of the form to be clickable. With the code here it works like that. The real problem is at the beginning when I want to input some text.

回答1:

The NoActivate flag isn't very well respected by Windows. You might have better luck rejecting the click message.

private const int WM_MOUSEACTIVATE = 0x0021, MA_NOACTIVATE = 0x0003;

protected override void WndProc(ref Message m) {
  if (m.Msg == WM_MOUSEACTIVATE) {
     m.Result = (IntPtr)MA_NOACTIVATE;
     return;
  }
  base.WndProc(ref m);
}

that will let the click go through to the next window down. If you want to block the click entirely, use MA_NOACTIVATEANDEAT = 0x0004 instead of MA_NOACTIVATE

If you don't need such strong protection, there is another flag you can override:

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


回答2:

After searching even more around the Internet I found a simple one line solution:

Activate();

Didn't know this existed. Using the code in the question plus this on Form_Load I can have the program active at the beginning and stays that way until I change to another program. After that my program will never be active again. Unless I put a button or something that calls Activate() again.



标签: c# forms