Domanda

I have noticed some strange form interactions while using a ContextMenuStrip or a MenuStrip. I don't really know what is causing it so the following should create a repeatable test for anyone looking into this:

I've created two Windows Forms: Form1 and Form2. Both have a MenuStrip added to them. Both are set to StartPosition = CenterScreen.

Form1 has a simple menu like this: Form2 > Open. Clicking "Open" will launch Form2.

Form2 has a simple menu like this: Try to open > anotherTestMenuItem

  1. Start the program. Form1 opens.
  2. Open Form2 from Form1 (i.e. click Form2 > Open).
  3. Form2 appears.
  4. On Form2, try to open the MenuStrip (click Try to open). Form1 will reappear over Form2, although Form2 still has focus (you can see this if you move Form2 a little before trying to open the menu).

If I set Form2's owner to Form1, Form2 remains visible when you try Step 4, but the menu doesn't display the first time. All subsequent clicks seem fine.

I noticed this when I tried opening a context menu (on a form opened by another form) and it would disappear immediately, but only the first time. Every time thereafter it would open normally.

Does anyone have any ideas as to what is going on?

È stato utile?

Soluzione

Yes, this is a known bug in the RTM version of .NET 4.5. This KB article mentions it:

When you click a menu item to open a child window in the application, interactions with the menu and child windows behave incorrectly.

For example, you may experience the following:
- When you open a shortcut menu in the child window, the main window form takes the focus.
- You cannot use mnemonics to access a menu item.

As you can tell from the KB article, this bug was fixed quite a while ago. The bug fix was incorporated in a maintenance release first made available on January 8th of 2013. Be sure to allow Windows Update to deploy that update on your machine. Or download it from here.

Altri suggerimenti

Check to see that you have:

"AutoValidate" set to "EnablePreventFocusChange"

Make sure you do not call the Hide method for a menu or contextmenu during its item-click handler. I was in the habit of doing this during development to get a menu off the screen while I stepped through debugging code. However when I launched a secondary form from such a menu, the first right-click in the new form would cause the focus to revert to the primary form, sometimes even if I had left-clicked or typed something in the new form. I don't recall if I found this solution online somewhere or discovered it myself. This may not be the same bug mentioned above, but this behavior still occurs in .NET 4.7.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top