2014-01-18 77 views
1

我正在创建一个程序来管理本地网络,但我有一个小问题。 当表格开始时,它开始隐藏。键盘快捷键显示隐藏表格

我用这个代码隐藏:

Protected Overrides Sub SetVisibleCore(ByVal value As Boolean) 
    If Not Me.IsHandleCreated Then 
     Me.CreateHandle() 
     value = False 
    End If 
    MyBase.SetVisibleCore(value) 
End Sub 

我想恰恰是展现形式,当我点击ALT +X例如。

+1

可能重复[VB.NET检测按键虽然最小化](http://stackoverflow.com/questions/5216222/vb-net-detecting-keypress-while-minimized) –

回答

2

使用全局热键。这样你就不必担心你的应用程序有重点。对于VB.Net一个很好的例子是在这里:

http://www.kirsbo.com/How_to_add_global_hotkeys_to_applications_in_VB.NET

来概括。定义热键类:

Public Class Hotkey 

#Region "Declarations - WinAPI, Hotkey constant and Modifier Enum" 
     ''' <summary> 
     ''' Declaration of winAPI function wrappers. The winAPI functions are used to register/unregister a hotkey 
     ''' </summary> 
     Public Declare Function RegisterHotKey Lib "user32" _ 
     (ByVal hwnd As IntPtr, ByVal id As Integer, ByVal fsModifiers As Integer, ByVal vk As Integer) As Integer 

     Public Declare Function UnregisterHotKey Lib "user32" (ByVal hwnd As IntPtr, ByVal id As Integer) As Integer 

     Public Const WM_HOTKEY As Integer = &H312 

     Enum KeyModifier 
      None = 0 
      Alt = &H1 
      Control = &H2 
      Shift = &H4 
      Winkey = &H8 
     End Enum 'This enum is just to make it easier to call the registerHotKey function: The modifier integer codes are replaced by a friendly "Alt","Shift" etc. 
#End Region 


#Region "Hotkey registration, unregistration and handling" 
     Public Shared Sub registerHotkey(ByRef sourceForm As Form, ByVal triggerKey As String, ByVal modifier As KeyModifier) 
      RegisterHotKey(sourceForm.Handle, 1, modifier, Asc(triggerKey.ToUpper)) 
     End Sub 
     Public Shared Sub unregisterHotkeys(ByRef sourceForm As Form) 
      UnregisterHotKey(sourceForm.Handle, 1) 'Remember to call unregisterHotkeys() when closing your application. 
     End Sub 
     Public Shared Sub handleHotKeyEvent(ByVal hotkeyID As IntPtr) 
      MsgBox("The hotkey was pressed") 
     End Sub 
#End Region 

    End Class 

以下Sub然后添加到您的主要形式有:

'System wide hotkey event handling 
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) 
    If m.Msg = Hotkey.WM_HOTKEY Then 
    Hotkey.handleHotKeyEvent(m.WParam) 
    End If 
    MyBase.WndProc(m) 
End Sub 

然后注册在启动代码热键为您的表单:

Hotkey.RegisterHotKey(Me, "X", Hotkey.KeyModifier.Alt) 

第一参数是形式,第二个是要处理的关键,第三个是修饰键。一旦这个热键被注册,它将触发代码HotKey.handleHotKeyEvent

然后,您可以使用某种回调来触发调用表单中的方法,如果您愿意的话。

+0

你应该包括相关的代码链接在您的答案中,以防链接在未来中断。然后,您可以将该链接列为来源。 –

+0

@CodeMaverick好主意。沉迷于简洁没有很好的理由。 –

+0

Abs sol ute ly。 –