2011-07-13 20 views
1

今天我對我的WPF用戶界面有了一些新的限制,消除了MenuBar的永久可見性。如何使WPF MenuBar visibile按ALT鍵時?

我想過模仿Windows Live Messenger的用戶界面。只有在按下ALT鍵的情況下,該應用程序纔會顯示MenuBar。並且在MenuBar的焦點丟失時再次隱藏它。

目前我沒有線索如何在WPF中構建這樣的事情...是這樣的可能嗎?

在此先感謝。

回答

4

你可以寫在主窗口中的一個關鍵按下事件..

KeyDown="Window_KeyDown" 

和代碼隱藏文件..

private void Window_KeyDown(object sender, KeyEventArgs e) 
     { 
      if (e.Key == Key.LeftAlt || e.Key == Key.RightAlt) 
      { 
       myMenu.Visibility = Visibility.Visible; 
      } 
     } 
如果你想與MVVM或使用綁定來實現這一目標

...喲你可以使用輸入鍵綁定

<Window.InputBindings> 
     <KeyBinding Key="LeftAlt" Command="{Binding ShowMenuCommand}"/> 
     <KeyBinding Key="RightAlt" Command="{Binding ShowMenuCommand}"/> 
    </Window.InputBindings> 
+0

猜猜這是僅次於作業的代碼。 MVVM確實適合,但不應該用於這個我猜。試過了,它工作。但是,在所有的答案中,我都懷念菜單欄將再次崩潰的部分。 –

+0

您可以使用LostFocus或LostKeyboardFocus事件來處理摺疊菜單... – Bathineni

+0

我已經使用了上述解決方案。也增加了Key.System。但是,所有LostFocus事件似乎都不能正常工作。只有MenuBar.IsMouseCaptureWithinChanged事件才能正確執行作業。 –

0

這是我的理解:

private void form_KeyDown(object sender, 
    System.Windows.Forms.KeyEventArgs e) 
{ 
    if(e.KeyCode == Keys.Alt && /*menu is not displayed*/) 
    { 
     // display menu 
    } 
} 

private void form_KeyUp(object sender, 
    System.Windows.Forms.MouseEventArgs e) 
{ 
    if (/*check if mouse is NOT over menu using e.X and e.Y*/) 
    { 
     // hide menu 
    } 
} 

如果你需要不同的東西打了一下用鍵盤和鼠標事件。

+1

看起來不像WPF我 – CodesInChaos

0

可以使用的KeyDown(或預覽版本,如果你喜歡),然後檢查是否有這樣的系統關鍵:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     this.KeyDown += new KeyEventHandler(MainWindow_KeyDown); 
    } 

    void MainWindow_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.System && (Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) 
     { 
      // ALT key pressed! 
     } 
    } 
} 
1

我認爲正確的實現是用KeyUp。這是IE8,Vista中,Windows7的等近期微軟產品的行爲:

private void MainWindow_KeyUp(Object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.System) 
     { 
      if (mainMenu.Visibility == Visibility.Collapsed) 
       mainMenu.Visibility = Visibility.Visible; 
      else 
       mainMenu.Visibility = Visibility.Collapsed; 
     } 
    } 
+0

這確實是系統的關鍵。 –