Active process and shortcut keys

R

Rotsey

Hi,

I am writing app that I want to be able to hit a shortcut
key (windows wide) and have it all launch my app and then
be able to get the name of the process that was active when
the key was pressed.

Is this possible and how?

I know I can assign a shortcut key to the app but how do
I get the active process name?

rotsey
 
N

Newbie Coder

G'day Malcolm,

This is an example to register the current app to be launched via a global
hotkey. Adapt it for your own purposes.

If you notice atom name is the name of this application which you need to
change. As you're hard coding you will have the process name too

Remember to pass the process name to the application for unregistering the
hotkey

Imports System.Runtime.InteropServices

#Region "Declarations"

Private Declare Function RegisterHotKey Lib "user32" (ByVal hwnd As IntPtr,
ByVal id As _
Integer, ByVal fsModifiers As Integer, ByVal vk As Integer) As Integer
Private Declare Function UnregisterHotKey Lib "user32" (ByVal hwnd As
IntPtr, ByVal id _
As Integer) As Integer
Private Declare Function GlobalAddAtom Lib "kernel32" Alias "GlobalAddAtomA"
(ByVal _
lpString As String) As Short
Private Declare Function GlobalDeleteAtom Lib "kernel32" (ByVal nAtom As
Short) As Short

Private Const MOD_ALT As Integer = 1
Private Const MOD_CONTROL As Integer = 2
Private Const MOD_SHIFT As Integer = 4
Private Const MOD_WIN As Integer = 8

Dim hotkeyID As Short

#End Region

#Region "Register Global HotKey (SUB)"

' register a global hot key
Private Sub RegisterGlobalHotKey(ByVal hotkey As Keys, ByVal modifiers As
Integer)
Try
' use the GlobalAddAtom API to get a unique ID (as suggested by MSDN
docs)
Dim atomName As String = AppDomain.GetCurrentThreadId.ToString("X8")
& Me.Name
hotkeyID = GlobalAddAtom(atomName)
If hotkeyID = 0 Then
Throw New Exception("Unable to generate unique hotkey ID. Error
code: " & _
Marshal.GetLastWin32Error().ToString)
End If

' register the hotkey, throw if any error
If RegisterHotKey(Me.Handle, hotkeyID, modifiers, CInt(hotkey)) = 0
Then
Throw New Exception("Unable to register hotkey. Error code: " &
_
Marshal.GetLastWin32Error.ToString)
End If
Catch ex As Exception
' clean up if hotkey registration failed
UnregisterGlobalHotKey()
End Try
End Sub

#End Region

#Region "Unregister Global HotKey (SUB)"

' unregister a global hotkey
Private Sub UnregisterGlobalHotKey()
If Me.hotkeyID <> 0 Then
UnregisterHotKey(Me.Handle, hotkeyID)
' clean up the atom list
GlobalDeleteAtom(hotkeyID)
hotkeyID = 0
End If
End Sub

#End Region

Useage:

RegisterGlobalHotKey(Keys.F6, MOD_SHIFT Or MOD_CONTROL)

or

UnregisterGlobalHotKey()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top