Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I cancel a ContextMenu programmatically?

First keep track of which control is showing the ContextMenu by listening to the menu's Popup event and querying for the SourceControl.

Then when you are ready to cancel the popup, do as follows:

[DllImport("user32.dll", CharSet=CharSet.Auto)]
extern internal static IntPtr SendMessage(IntPtr hWnd, int msg,
  IntPtr wParam, IntPtr lParam);

private void Timer_Tick(object sender, EventArgs e)
{
  if ( menuSourceControl != null )
    SendMessage(menuSourceControl.Handle, 0x001F/*WM_CANCELMODE*/,
      IntPtr.Zero, IntPtr.Zero);
}

Contributed from George Shepherd's Windows Forms FAQ