我正在创建一个程序,它将发送媒体键输入(例如MediaPlayPause
, MediaNextTrack
等)到我有的应用程序IntPtr
的。有点像虚拟遥控器。
所以经过研究我发现this, which almost准确地告诉我如何解决我的问题。
然而,链接中提到的方法存在三个问题。
- 我无法将应用程序设置为前台窗口,因为我需要聚焦我的应用程序。
- 他们使用 SendKeys 函数,该函数要求目标窗口获得焦点,这与问题 1 背道而驰。
- 据我所知,SendKeys无法发送键盘按钮,例如键盘播放/暂停按钮。
最后,我对我必须使用什么感到相当困惑(SendInput
?, SendMessage
?).
任何帮助,将不胜感激。
EDIT
根据我收到的答案,我将下面的示例代码组合在一起。
理论上,它应该找到记事本并将字母“L”插入其中。
但是,记事本上没有显示任何内容,应用程序也没有崩溃。我遗漏了一个明显的错误吗?
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(int ZeroOnly, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, IntPtr lParam);
const int WM_KEYDOWN = 0x100;
//const int WM_KEYUP = 0x101;
const int L_KEY = 0x4C;
private void button1_Click(object sender, EventArgs e)
{
IntPtr ip = FindWindowByCaption(0, "Untitled - Notepad");
SendMessage(ip, WM_KEYDOWN, L_KEY, IntPtr.Zero);
//SendMessage(ip, WM_KEYUP, L_KEY, IntPtr.Zero);
}