tags:

views:

167

answers:

1

I have a WPF TaskBar like application that i am developing for fun and i want to be able to open the System Menu for the application (that is in my custom taskbar) that i right click on, preserving any custom menu that the app might create (i.e. Google Chrome). I have the following code that works for a borderless window app i made previously, but it doesn't seem to work and i am wondering why? And what do i need to do to get it to work?

     public static void ShowContextMenu(IntPtr hWnd)
 {
  SetForegroundWindow(hWnd);
  IntPtr wMenu = GetSystemMenu(hWnd, false);
  // Display the menu
  uint command = TrackPopupMenuEx(wMenu,
   TPM.LEFTBUTTON | TPM.RETURNCMD, 0, 0, hWnd, IntPtr.Zero);
  if (command == 0)
   return;

  PostMessage(hWnd, WM.SYSCOMMAND, new IntPtr(command), IntPtr.Zero);
 }

Tip: It appears that TrackPopupMenuEx(...) returns immediately with the value of 0, instead of waiting for a response...

+1  A: 

It appears there is an issue with giving TrackPopupMenuEx the owner window handle of the Menu... instead i used the handle of my wpf window and then when posting the message, i used the Menu's owner... seems a bit strange to me but it works!

     public static void ShowContextMenu(IntPtr hAppWnd, Window taskBar, System.Windows.Point pt)
 {
  WindowInteropHelper helper = new WindowInteropHelper(taskBar);
  IntPtr callingTaskBarWindow = helper.Handle;
  IntPtr wMenu = GetSystemMenu(hAppWnd, false);
  // Display the menu
  uint command = TrackPopupMenuEx(wMenu,
   TPM.LEFTBUTTON | TPM.RETURNCMD, (int) pt.X, (int) pt.Y, callingTaskBarWindow, IntPtr.Zero);
  if (command == 0)
   return;

  PostMessage(hAppWnd, WM.SYSCOMMAND, new IntPtr(command), IntPtr.Zero);
 }
David Rogers