2016-05-25 87 views
0

我在vb.net中製作應用程序,當它在任何編輯器中運行時檢測到鍵盤的擊鍵。現在我可以得到擊鍵,這很容易,但我想知道應用程序的名稱,如果用戶正在寫在記事本中,那麼我想要那個名字。 請任何人都可以提出任何想法。 感謝在VB.net中從鍵盤輸入獲取應用程序名稱

回答

0

您需要使用的Windows API:

Private Sub Main() 
    Dim shortName as String = GetShortEXEName(GetForegroundWindow()) 
End Sub 

' Define other methods and classes here 
<DllImport("user32.dll", SetLastError := True)> _ 
Public Shared Function GetForegroundWindow() As IntPtr 
End Function 

Public Shared Function GetProcess(hwnd As IntPtr) As Process 
    Dim intID As Integer = 0 
    GetWindowThreadProcessId(hwnd, intID) 
    Return Process.GetProcessById(intID) 
End Function 

<DllImport("user32.dll", SetLastError := True)> _ 
Public Shared Function GetWindowThreadProcessId(hwnd As IntPtr, ByRef lpdwProcessId As Integer) As Integer 
End Function 

Public Shared Function GetShortEXEName(hwnd As IntPtr) As String 
    ' this seems to be better to use than calling GetProcessEXEName and then using substring functions to get the short executable name 
    ' because that function seems to crash when dealing with Windows Explorer windows 
    Try 
     Return GetProcess(hwnd).ProcessName 
    Catch 
     Return "" 
    End Try 
End Function