Question

I am converting my winforms project over to WPF and also learning WPF while i am doing it.

I ran into a problem with this code

This code detects the buttons pressed on a media keyboard or Media Center remote control.

Protected Overrides Sub WndProc(ByRef msg As Message)
    If msg.Msg = &H319 Then
        ' WM_APPCOMMAND message
        ' extract cmd from LPARAM (as GET_APPCOMMAND_LPARAM macro does)
        Dim cmd As Integer = CInt(CUInt(msg.LParam) >> 16 And Not &HF000)
        Select Case cmd
            Case 13
                MessageBox.Show("Stop Button")
                Exit Select
            Case 47
                MessageBox.Show("Pause Button")
                Exit Select
            Case 46
                MessageBox.Show("Play Button")
                Exit Select
        End Select
    End If
    MyBase.WndProc(msg)
end sub

I was wondering if there was a way to get it working in WPF or maybe do something similar.

Edit

My latest attempt, i tried to convert it from C# so it maybe be incorrect. (this just crashes my app)

Dim src As HwndSource = HwndSource.FromHwnd(New WindowInteropHelper(Me).Handle)
src.AddHook(New HwndSourceHook(AddressOf WndProc))

and

Public Function WndProc(hwnd As IntPtr, msg As Integer, wParam As IntPtr, lParam As IntPtr, ByRef handled As Boolean) As IntPtr

'Do something here
If msg = "WM_APPCOMMAND" Then
MessageBox.Show("dd")
End If

Return IntPtr.Zero
End Function

Am i on the right track or am i way off?

Was it helpful?

Solution

Your window procedure is wrong:

Public Function WndProc(hwnd As IntPtr, msg As Integer, wParam As IntPtr, lParam As IntPtr, ByRef handled As Boolean) As IntPtr

    'Do something here
    If msg = "WM_APPCOMMAND" Then
        MessageBox.Show("dd")
    End If

    Return IntPtr.Zero
End Function

Note that the msg parameter is an Integer, not a string. This should be giving you a compile-time error, so I don't know what you mean about it crashing your app, though.

You need the Windows header files to find out the ID of the WM_APPCOMMAND message, or they're sometimes given in the documentation. In this case, it is. The value is &H0319 (in VB hex notation).

So change the code to look like this:

Private Const WM_APPCOMMAND As Integer = &H0319

Public Function WndProc(hwnd As IntPtr, msg As Integer, wParam As IntPtr, lParam As IntPtr, ByRef handled As Boolean) As IntPtr

    ' Check if the message is one you want to handle
    If msg = WM_APPCOMMAND Then
        ' Handle the message as desired
        MessageBox.Show("dd")

        ' Indicate that you processed this message
        handled = True
    End If

    Return IntPtr.Zero
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top