Some of you (like me), probably noticed that a ContextMenuStrip ("Right Click Menu") doesn't close automatically if you click outside it and it isn't in a form (in Visual Basic 2008, but i don't know about the later versions). So in this article I'll explain how to solve that "bug". We'll be using as example a ContextMenuStrip on a NotifyIcon ("Tray Icon"), because I think that is the most common use of a ContextMenuStrip outside a form. In this article:
If e.Button = Windows.Forms.MouseButtons.Right Then 'Checks if the pressed button is the Right Mouse trayform.Show() 'Shows the Form that is the parent of "traymenu" trayform.Activate() 'Set the Form to "Active", that means that that will be the "selected" window trayform.Width = 1 'Set the Form width to 1 pixel, that is needed because later we will set it behind the "traymenu" trayform.Height = 1 'Set the Form Heigth to 1 pixel, for the same reason as above End If
traymenu.Show(Cursor.Position) 'Shows the Right click menu on the cursor position Me.Left = traymenu.Left + 1 'Puts the form behind the menu horizontally Me.Top = traymenu.Top + 1 'Puts the form behind the menu vertically
Me.Close() 'Closes the "trayform" Form and consequently every thing in it, including the "traymenu"
Form1.tray.Visible = False 'Hides the tray icon. if we don't do this we can kill the app, but the icon will still be there End 'Kills the application ↑Return to Top
↑Return to Top