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

时间:2011-12-22 14:17:03

标签: c# command keyboard-events

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

这是我到目前为止的代码,但是我还没有弄清楚如何将键盘命令发送到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);
    }
}

4 个答案:

答案 0 :(得分:9)

[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。

答案 1 :(得分:6)

SendMessage正是您正在寻找的。 也许您的问题已在此处解决:How to send text to Notepad in C#/Win32?

答案 2 :(得分:6)

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

但您基本上会使用低级别的c调用将消息放入Windows消息队列,以允许应用程序接收按键。

PostMessage

SendMessage

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

所有代码都已签入GitHub:https://github.com/EasyAsABC123/Keyboard

答案 3 :(得分:1)

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

只需sample