VB.NET 간단한 후킹을 통해 단축키 생성하기

2022. 11. 29. 14:44VB.NET

VB.NET 간단한 후킹을 통해 단축키 생성하기

내가 만든 프록그램이 forground이든 background이든 관계없이, 다른 프로그램이 윈도우 포커스를 갖고 있다고 해도 윈도우 어디서든 내가 만든 단축키를 누르면 내 프로그램이 실행되도록 만들 수 있다.

아래 소스는 가장 기본이 되는 부분만 추가하여 Ctrl+B를 누르면 어디서든 내 프로그램 안에 있는 버튼이 눌려지게 만든 간략한 소스이다.

아쉬운 순간이 있으니 필요할때마다 참고하자.

기본 윈도우 form 프로젝트에 버튼하나 (Button1)만 올려놓고 아래 소스를 그대록 복붙하면 된다.

Public Class FormMain

    Declare Function RegisterHotKeyA Lib "user32" Alias "RegisterHotKey" (ByVal itp As IntPtr, ByVal id As Integer, ByVal fsInform As KeyInform, ByVal vk As Keys) As Boolean
    Declare Function UnregisterHotKeyA Lib "user32" Alias "UnregisterHotKey" (ByVal itp As IntPtr, ByVal id As Integer) As Boolean

    Const KEYid As Integer = 31197
    Const HOTKEYGap As Integer = &H312

    Public Enum KeyInform
        None = 0
        Alt = 1
        Control = 2
        Shift = 4
        Windows = 8
    End Enum

    Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        RegisterHotKeyA(Me.Handle, KEYid, KeyInform.Control, Keys.B)   ' 단축키 추가
    End Sub

    Protected Overrides Sub WndProc(ByRef m As Message)
        If m.Msg = HOTKEYGap Then
            Dim key As Keys = (CInt(m.LParam) >> 16) And &HFFFF
            Dim modifier As KeyInform = CInt(m.LParam) And &HFFFF
            If KeyInform.Control = modifier And Keys.B = key Then   ' 단축키 실행
                Button1.PerformClick()
            End If
        End If
        MyBase.WndProc(m)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MsgBox("눌려짐")
    End Sub

    Private Sub FormMain_Closed(sender As Object, e As EventArgs) Handles Me.Closed
        UnregisterHotKeyA(Me.Handle, KEYid)       ' 단축키 제거
    End Sub
End Class
반응형