wpf實現IE菜單欄自動隱藏效果

IE菜單欄默認爲隱藏狀態,按下鍵盤Alt鍵後顯示,菜單失去焦點則自動隱藏。下面說說WPF中如何實現這樣的效果。web

第一步:Menu默認設置爲隱藏(Visibility="Collapsed"),這裏不該該設置爲"Hidden",由於菜單欄隱藏後其餘控件須要自動填補菜單欄隱藏後的空缺。Visibility="Hidden"只是界面上不顯示而已,Menu控件的位置仍是被佔用着。this

第二步:響應鍵盤Alt鍵,而後顯示出Menu。這裏須要用到WPF中的隧道事件(PreviewXXX),從根元素開始響應,這樣不論焦點在哪一個控件上,都能獲得KeyDown事件。例子中是在Window根節點添加PreviewKeyDown事件。spa

第三步:響應鍵盤焦點(KeyboardFocus),GotFocus則顯示,LostFocus則隱藏。日誌

第四步:因爲還能經過鍵盤組合鍵的方式來打開菜單,因此還要響應ContextMenuOpening事件,不論Menu因爲什麼緣由Opening了,菜單欄都須要爲顯示狀態。code

複製代碼
<Window x:Class="IEMenu.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" PreviewKeyDown="Window_PreviewKeyDown">
    <DockPanel>
        <Menu x:Name="menu" DockPanel.Dock="Top" VerticalAlignment="Top" Visibility="Collapsed"
              GotKeyboardFocus="menu_GotKeyboardFocus"
              LostKeyboardFocus="menu_LostKeyboardFocus"
              ContextMenuOpening="menu_ContextMenuOpening">
            <MenuItem Header="文件(_F)">
                <MenuItem Header="打開(_O)..." />
                <MenuItem Header="保存(_S)" />
                <MenuItem Header="另存爲(_A)..." />
                <Separator />
                <MenuItem Header="退出(_Q)" />
            </MenuItem>
            <MenuItem Header="幫助(_H)">
                <MenuItem Header="清除日誌(_C)" Click="MenuItem_Click" />
                <MenuItem Header="幫助(_H)" />
                <Separator />
                <MenuItem Header="關於(_A)" />
            </MenuItem>
        </Menu>
        <Border Background="Aquamarine" BorderBrush="Black" BorderThickness="5" CornerRadius="10">
            <ListBox x:Name="log" />
        </Border>
    </DockPanel>
</Window>
複製代碼

 

後臺代碼以下:orm

複製代碼
private void menu_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
    menu.Visibility = Visibility.Visible;
}

private void menu_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
    menu.Visibility = Visibility.Collapsed;
}

private void menu_ContextMenuOpening(object sender, ContextMenuEventArgs e) {
    menu.Visibility = Visibility.Visible;
}

private void Window_PreviewKeyDown(object sender, KeyEventArgs e) {
    if(e.SystemKey == Key.LeftAlt || e.SystemKey == Key.RightAlt) {
        if(menu.Visibility != Visibility.Visible) menu.Visibility = Visibility.Visible;
    }
}
複製代碼
相關文章
相關標籤/搜索