1

我正在将我的 winforms 项目转换为 WPF,并在我这样做的同时学习 WPF。

我遇到了这段代码的问题

此代码检测媒体键盘或媒体中心遥控器上按下的按钮。

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

我想知道是否有办法让它在 WPF 中工作,或者做类似的事情。

编辑

我最近的尝试,我试图从 C# 转换它,所以它可能是不正确的。(这只是让我的应用程序崩溃)

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

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

我是在正确的轨道上还是我走错了路?

4

1 回答 1

3

您的窗口过程是错误的:

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

请注意,msg参数是一个Integer,而不是字符串。这应该会给你一个编译时错误,所以我不知道你的意思是什么让你的应用程序崩溃。

您需要 Windows 头文件来找出WM_APPCOMMAND消息的 ID,或者有时会在文档中给出它们。在这种情况下,它是。该值为&H0319(在 VB 十六进制表示法中)。

因此,将代码更改为如下所示:

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
于 2013-08-02T16:27:26.350 回答