2013-06-21 23 views
1

我想更改我的WPF主窗口中圖標的行爲。我已經知道如何改變它的外觀 - 根據需要將圖標設置爲ImageSource。我希望完成的是,當點擊圖標時,我自己的自定義菜單將打開,而不是標準的打開/關閉/最小化選項。如何更改WPF中的圖標行爲?

任何想法?

+0

我認爲沒有簡單的解決方案。我可以告訴一個。我們需要創建自己的模板窗口,並用'TextBlock'設置它的'Image'。我們用圖標得到標題。然後設置圖像的處理程序(MouseLeftButtonDown),它將用您的命令打開'ContextMenu'。 –

+0

@Tal Malaki,你在Windows 7嗎? –

+0

不,我在Windows 2008和Visual Studio 2012. –

回答

0

將此代碼放置在您的WPF窗口中。您可能需要稍微調整一下代碼,但這完全符合您的要求。它只適用於右鍵點擊圖標。如果您需要左鍵點擊,則使用WM_NCLBUTTONDOWN作爲消息。

它通過攔截當前窗口上的本機窗口消息來工作。 WM_NC *消息負責溝通窗口鑲邊事件。一旦你截獲了這些事件,你只需要在正確的位置顯示上下文菜單。

protected override void OnSourceInitialized(EventArgs e) 
    { 
     base.OnSourceInitialized(e); 
     HwndSource source = PresentationSource.FromVisual(this) as HwndSource; 
     source.AddHook(WndProc); 
    } 

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) 
    { 
     if (msg == 0xA4) //WM_NCRBUTTONDOWN 
     { 
      //Screen position of clicked point 
      var pos = new Point(lParam.ToInt32() & 0xffff, lParam.ToInt32() >> 16); 

      //Check if we clicked an icon these values are not precise 
      // and could be adjusted 
      if ((pos.X - Left < 20) && (pos.Y - Top < 20)) 
      { 
       //Open up context menu, should be replaced with reference to your 
       // own ContextMenu object 
       var context = new ContextMenu(); 
       var item = new MenuItem { Header = "Test" }; 
       context.Items.Add(item); 
       item.Click += (o,e) => MessageBox.Show("Hello World!"); 

       //Those are important properties to set 
       context.Placement = PlacementMode.AbsolutePoint; 
       context.VerticalOffset = pos.Y; 
       context.HorizontalOffset = pos.X; 
       context.IsOpen = true; 

       handled = true; 
      } 
     } 

     return IntPtr.Zero; 
    } 
+0

好吧,但是如果我想按下單詞Test將調用一個事件怎麼辦? –

+0

@Tal Malaki只需將項目處理程序添加到MenuItem,就像在標準WPF菜單中一樣。例如,請參閱我編輯的答案。 – ghord