2010-02-17 98 views
2

我有自定義樣式的非矩形透明窗口。如何以編程方式調用應用程序菜單?

<Window 
    x:Class="TestWindow" x:Name="Window" 
    Width="350" Height="450" AllowsTransparency="True" WindowStyle="None" 
WindowStartupLocation="CenterScreen" FontSize="14 px" FontFamily="Fonts/#Tahoma" 
Background="Transparent"> 

我有一個標題和系統按鈕的網格,並希望通過右鍵單擊它顯示應用程序菜單。目前的應用程序菜單僅通過按下ALT +空格鍵顯示。 我該如何解決這個問題?

回答

4

因此,在Google花了兩個小時後,我終於找到了解決方案。

第一步:確定RECT結構是這樣的:

[StructLayout(LayoutKind.Sequential)] 
public struct RECT 
    { 
      public int Left; 
      public int Top; 
      public int Right; 
      public int Bottom; 
    } 

第二步:輸入2 user32.dll中的功能:

[DllImport("user32.dll")] 
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert); 

[DllImport("user32.dll")] 
public static extern int TrackPopupMenu(int hMenu, int wFlags, int x, int y, int nReserved, int hwnd, ref RECT lprc); 

第三步:添加 '鼠標右鍵點擊標題' 事件處理程序:

private void headerArea_PreviewMouseDown(object sender, MouseButtonEventArgs e) 
     {    
      switch (e.ChangedButton) 
      { 
       case MouseButton.Right: 
        { 
         // need to get handle of window 
         WindowInteropHelper _helper = new WindowInteropHelper(this); 

         //translate mouse cursor porition to screen coordinates 
         Point p = PointToScreen(e.GetPosition(this)); 

         //get handler of system menu 
         IntPtr systemMenuHandle = GetSystemMenu(_helper.Handle, false); 

         RECT rect = new RECT(); 
         // and calling application menu at mouse position. 
         int menuItem = TrackPopupMenu(systemMenuHandle.ToInt32(), 1,(int)p.X, (int) p.Y, 0, _helper.Handle.ToInt32(), ref rect); 
         break; 
        }     
      } 
     } 
1

我不得不改變Raeno的代碼如下,讓菜單項工作...

//Get the hWnd, because I need to re-use it... 
int hWnd = helper.Handle.ToInt32(); 
//Change the wFlags from 1 to TPM_RIGHTBUTTON | TPM_RETURNCMD... 
int menuItem = TrackPopupMenu(systemMenuHandle.ToInt32(), TPM_RIGHTBUTTON | TPM_RETURNCMD, (int)point.X, (int)point.Y, 0, hWnd, ref rect); 

// The return value from TrackPopupMenu now need posting... 
if (menuItem != 0) 
{ 
    PostMessage(hWnd, WM_SYSCOMMAND, menuItem, 0); 
} 

這就需要下面的聲明...

private const int WM_SYSCOMMAND = 0x0112; 
private const int TPM_RIGHTBUTTON = 0x0002; 
private const int TPM_RETURNCMD = 0x0100; 

[DllImport("User32.dll")] 
public static extern int PostMessage(int hWnd, int Msg, int wParam, int lParam); 
相關問題