2016-12-28 104 views
3

我試圖模擬Windows資源管理器菜單欄(win7)的行爲。像Windows資源管理器菜單欄自動隱藏MenuStrip

我檢查了this question,它不符合我的要求。

預期的行爲:

  • 按下Alt鍵關鍵 ==>撥動MenuStripvisible財產。
  • 替代 + access key char ==>顯示MenuStrip並打開目標菜單。
  • 與窗體中的任何其他區域進行交互(即,取消激活MenuStrip)==>隱藏MenuStrip

我 「最小的,完整的和可覈查」 代碼:

Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    Me.KeyPreview = True 
    menuBar.Visible = False 
End Sub 

Private Sub frmMain_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp 
    If e.KeyCode = Keys.Menu Then ' Requirement #1 
     menuBar.Visible = Not menuBar.Visible 
    End If 
End Sub 

Private Sub frmMain_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown 
    If e.Alt AndAlso e.KeyCode <> Keys.Menu Then ' Requirement #2 
     menuBar.Visible = True 
    End If 
End Sub 

Private Sub menuBar_MenuDeactivate(sender As Object, e As EventArgs) Handles menuBar.MenuDeactivate 
    menuBar.Visible = False ' Requirement #3 
End Sub 

問題:

當按下Alt鍵鍵的同時MenuStrip是可見的,事件MenuDeactivate被觸發並且MenuStrip在01上被隱藏,然後在KeyUp上再次顯示。

我嘗試添加一個布爾值,它KeyDown事件設置爲false,然後將其設置爲true KeyUp事件,所以設置menuBar.Visible = False之前,我可以檢查它的價值,但是,出乎意料的事件KeyDown的​​事件是否是對之前MenuDeactivate火災表單或菜單條。

任何想法?

附註:雖然我的代碼在VB中,但歡迎使用C#代碼的任何答案。

回答

0

我設法弄清楚這個問題,這是簡單地檢查Alt鍵按鍵/在MenuDeactivate事件隱藏MenuStrip前按住,這樣的解決方法:

If Not My.Computer.Keyboard.AltKeyDown Then menuBar.Visible = False 

完整的實現如果有人有興趣

Private Sub frmMain_KeyUp(sender As Object, e As KeyEventArgs) Handles MyBase.KeyUp 
    If e.KeyCode = Keys.Menu Then 
     menuBar.Visible = Not menuBar.Visible 
    End If 
End Sub 

Private Sub frmMain_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown 
    If e.Alt AndAlso e.KeyCode <> Keys.Menu Then 
     menuBar.Visible = True 
    ElseIf e.KeyData = Keys.Escape Then 
     menuBar.Visible = False 
    End If 
End Sub 

Private Sub menuBar_MenuDeactivate(sender As Object, e As EventArgs) Handles menuBar.MenuDeactivate 
    If Not My.Computer.Keyboard.AltKeyDown Then menuBar.Visible = False 
End Sub 

希望它能幫助別人:)