【问题标题】:c# Sending keyboard commands to another window / processc# 将键盘命令发送到另一个窗口/进程
【发布时间】:2012-01-26 04:04:18
【问题描述】:

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

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

【问题讨论】:

标签: c# command keyboard-events


【解决方案1】:
[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();
    }
}

像这样试试。

【讨论】:

  • SendKeys 无法正常工作。假装另一个窗口被带到前台。在这种情况下,您会将密钥发送到错误的应用程序。
  • 抱歉复活了,但知道我怎么能做到这一点——通过互联网吗?我需要做同样的事情,但目标应用程序/进程正在另一台机器上运行!
  • 有人可以帮忙吗?我做到了,它的工作,但我遇到了一个大问题。我不能再次使用该表格。我创建了一个表单并放置了开始和停止按钮。但是我无法选择要单击停止的表单...有什么提示吗?泰!!!!
【解决方案2】:

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

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

PostMessage

SendMessage

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

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

【讨论】:

  • 如果我也想模拟 ModifierKeys 怎么办?
  • @deathrace 好问题!这似乎并不总是有效,因为它们是我发现的全局修饰符。所以我所做的是使用全局按键方法,然后按下背景键,它会接受按下的修饰符。然后我会取消他们的前景击键修饰符。通常击键是如此之短以至于它没有搞砸任何事情......但是,它总是让我感到困扰,因为它已经尽可能接近了,而不仅仅是向程序中注入了一个侦听 api 调用的 dll 击键。跨度>
【解决方案3】:

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

只是一个sample

【讨论】:

    猜你喜欢
    • 2010-09-29
    • 2011-06-14
    • 2020-09-14
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多