c#将键盘命令发送到另一个窗口/进程

我正在尝试编写一个程序,它将获取一行数据并将其传递到另一个窗口/进程。

这是我到目前为止的代码,但是我还没有弄清楚如何将键盘命令发送到OUTLOOK进程。

我希望能够使用Tab命令/键和Enter命令/键。

这是我到目前为止所尝试的

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; using System.Windows.Forms; namespace Config { class Program { [STAThread] static void Main(string[] args) { System.Threading.Thread.Sleep(30);//300000 TextReader tr = new StreamReader("config.txt"); Clipboard.SetText(tr.ReadLine()); tr.Close(); var proc = Process.GetProcessesByName("OUTLOOK").FirstOrDefault(); if (proc != null && proc.MainWindowHandle != IntPtr.Zero) { SetForegroundWindow(proc.MainWindowHandle); //SendKeys.Send("{ENTER}"); // Clipboard.GetText(); } } [DllImport("user32")] private static extern bool SetForegroundWindow(IntPtr hwnd); } } 

SendMessage是您正在寻找的。 也许你的问题在这里已经解决了: 如何在C#/ Win32中将文本发送到记事本?

 [DllImport("user32.dll")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); public void Start() { IntPtr zero = IntPtr.Zero; for (int i = 0; (i < 60) && (zero == IntPtr.Zero); i++) { Thread.Sleep(500); zero = FindWindow(null, "YourWindowName"); } if (zero != IntPtr.Zero) { SetForegroundWindow(zero); SendKeys.SendWait("{TAB}"); SendKeys.SendWait("{TAB}"); SendKeys.SendWait("{ENTER}"); SendKeys.Flush(); } } 

试试这样的smth。

我编写了几个向后台窗口发送按键的程序,我通常实现了PostMessage / SendMessage。 我在这里记录了我的所有发现!

但是你基本上会使用低级别的c调用将消息放入windows消息队列,以允许应用程序获取按键。

PostMessage的

发信息

如果您有任何问题,请告诉我,我的图书馆是用C#编写的,我很乐意与您分享。 此方法还允许在后台窗口中使用鼠标:)

所有代码都被检入GitHub: https : //github.com/EasyAsABC123/Keyboard

考虑到您知道何时以及将要发送到Outlook进程的键盘命令,您需要使用SendMessage Windows API函数。

只是一个样本