yitzih
yitzih

Reputation: 3118

Setting a hotkey for an executables shortcut in .NET

I have the following code (based on the instructions at https://msdn.microsoft.com/en-us/library/windows/desktop/bb773992(v=vs.85).aspx

Private Sub SetHotkey(FilePath As String)
    Const ssfPROGRAMS = 2            'Program Files

    Dim MyShell As Shell32.Shell = New Shell32.Shell
    Dim MyFolder As Shell32.Folder = MyShell.NameSpace(ssfPROGRAMS)

    If (MyFolder IsNot Nothing) Then
        Dim MyFolderItem As Shell32.FolderItem = MyFolder.ParseName(FilePath)
        If (MyFolderItem IsNot Nothing) Then
            Dim MyShellLink As ShellLinkObject = MyFolderItem.GetLink
            If (MyShellLink IsNot Nothing) Then
                MyShellLink.Hotkey = <<What goes here?>>
                MyShellLink.Save()
            End If
            MyShellLink = Nothing
        End If
        MyFolderItem = Nothing
    End If
End Sub

I am unsure which value to put as the Hotkey though. If for example I want to do Ctrl + Alt + A. what value would I put? (I would think Ctrl + Alt is 6 but i don't know how to put in the character key).

Upvotes: 1

Views: 92

Answers (3)

Idle_Mind
Idle_Mind

Reputation: 39122

Another example:

MyShellLink.Hotkey = MakeWord(Keys.A, HotKeyModifiers.Control Or HotKeyModifiers.Alt)

Using:

Public Enum HotKeyModifiers
    Shift = 1
    Control = 2
    Alt = 4
    Extended = 8
End Enum

Public Function MakeWord(ByVal loByte As Byte, ByVal hiByte As Byte) As Short
    Return Convert.ToInt16(loByte Or (hiByte << 8))
End Function

Upvotes: 1

djv
djv

Reputation: 15774

It says on linked page:

The virtual keyboard shortcut is in the low-order byte, and the modifier flags are in the high-order byte. The modifier flags can be a combination of the following values.

Find your key in Virtual-Key Codes. This will go in the low order byte. In your example, A has value 0x41, or decimal 65.

For the upper order byte, the modifiers are shift, ctrl, alt, and extended; equaling 1, 2, 4, and 8 respectively. Add up the values of the ones you want to use, in your case, ctrl + alt = 6. Then multiply this by 256 to shift it up one byte. This equals 1536.

Add 65 + 1536 = 1601. That is your hotkey for ctrl + alt + A

Upvotes: 1

shahkalpesh
shahkalpesh

Reputation: 33476

Here is how it goes

Based on this page, I figured that there is some bit twiddling happening here.

For example

(90 | (3 << 8)) returns 858 which is value of CTRL + SHIFT + Z

  1. In the above part, 90 is ASCII value of "Z".

  2. 3 is the value one gets by ORing 4 (for CTRL) with 1 (for SHIFT).

  3. The value that we get in step 2 is left shift by 8

  4. The value we get in step 3 is ORed with value in step 1

EDIT: The value for ALT is 4, CTRL is 2, SHIFT is 1

EDIT 2: For your example, the value for CTRL+ALT+A is (65 | (6 << 8)) which comes down to 1601.

Upvotes: 1

Related Questions