[英]C# PostMessage to Spotify
I am using C# to find and post the key press of Space (the keyboard shortcut for Pause/Play link ) to the Spotify application. 我正在使用C#查找并把Space的按键(Pause / Play 链接的键盘快捷键)发布到Spotify应用程序中。 I can successfully find the right window and copy the name of it using the first part of code. 我可以成功找到正确的窗口,并使用代码的第一部分复制它的名称。 But when I try to use the almost exact same code to post the message it won't work. 但是,当我尝试使用几乎完全相同的代码来发布消息时,它将无法工作。 I suspect there is something wrong with the PostMessage part but I can't figure out what. 我怀疑PostMessage部分出了问题,但我不知道是什么。
Code: 码:
private void button1_Click(object sender, EventArgs e)
{
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.ProcessName == "Spotify")
{
if (!p.MainWindowTitle.StartsWith("Spotify") && p.MainWindowTitle.Length > 0)
{
label1.Text = p.MainWindowTitle;
Console.WriteLine(label1.Text);
break;
}
else
{
label1.Text = "No Music";
}
}
}
}
[DllImport("user32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
private static Int32 WM_KEYDOWN = 0x0100;
private static Int32 WM_KEYUP = 0x0101;
private void button2_Click(object sender, EventArgs e)
{
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.ProcessName == "Spotify")
{
Console.WriteLine(p.MainWindowTitle);
if (p.MainWindowTitle.Length > 0)
{
PostMessage(p.MainWindowHandle, (uint)WM_KEYDOWN, (IntPtr)Keys.Space, IntPtr.Zero);
}
}
}
}
Thank you for any help you can provide 感谢您提供任何帮助
/Morgan /摩根
Send the key code of the multimedia Play/Pause key instead. 而是发送多媒体播放/暂停键的键代码。 The Spotify client listens for that. Spotify客户端会监听。
See this SO answer for details 看到这个SO答案的详细信息
Unfortunately for you, Spotify is not a native windows application. 对于您来说不幸的是,Spotify不是本机Windows应用程序。 It's mostly just a wrapper for Chrome, as far as UI is concerned. 就UI而言,它基本上只是Chrome的包装。 This is easily seen when using Spy++ - pressing Space in the Spotify window will not trigger any WM_KEYDOWN
message or anything similar. 使用Spy ++时很容易看到-在Spotify窗口中按Space不会触发任何WM_KEYDOWN
消息或类似消息。
It may be possible to find some other way of faking this (for example, WM_LBUTTONDOWN
seems to be sent properly), but applications avoiding windows messaging are generally much harder to automate. 也许可以找到其他伪造此方法的方式(例如, WM_LBUTTONDOWN
似乎已正确发送),但是避免Windows消息传递的应用程序通常很难自动化。
Fortunately, the application does respond to WM_COMMAND
. 幸运的是,该应用程序确实响应WM_COMMAND
。 The following works for me: 以下对我有用:
PostMessage(hwnd, WM_COMMAND, 0x18007D07, 0x000E0880);
I can't tell you how safe this is, though. 不过,我无法告诉您这有多安全。 wParam
will probably stay the same, since that's just the notification code and control ID. wParam
可能保持不变,因为那只是通知代码和控件ID。 I'm not sure about the lParam
, though. 我不确定lParam
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.