如何将 F4 键发送到 C# 中的进程? [英] How can I send the F4 key to a process in C#?

查看:20
本文介绍了如何将 F4 键发送到 C# 中的进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 Windows 应用程序启动一个进程.当我按下按钮时,我想模拟在该过程中按下 F4 键.我该怎么做?

I am starting a process from a Windows application. When I press a button I want to simulate the pressing of key F4 in that process. How can I do that?

[稍后编辑] 我不想在我的表单中模拟 F4 键的按下,而是在我开始的过程中.

[Later edit] I don't want to simulate the pressing of the F4 key in my form, but in the process I started.

推荐答案

要将 F4 键发送到另一个进程,您必须激活该进程

To send the F4 key to another process you will have to activate that process

http://bytes.com/groups/net-c/230693-activate-other-process 建议:

  1. 获取 Process.Start 返回的 Process 类实例
  2. 查询 Process.MainWindowHandle
  3. 调用非托管 Win32 API 函数ShowWindow"或SwitchToThisWindow"

然后您可以使用 System.Windows.Forms.SendKeys.Send("{F4}") 作为 Reed 建议将击键发送到此进程

You may then be able to use System.Windows.Forms.SendKeys.Send("{F4}") as Reed suggested to send the keystrokes to this process

下面的代码示例运行记事本并向其发送ABC":

The code example below runs notepad and sends "ABC" to it:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace TextSendKeys
{
    class Program
    {
        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        static void Main(string[] args)
            {
                Process notepad = new Process();
                notepad.StartInfo.FileName = @"C:WindowsNotepad.exe";
                notepad.Start();

                // Need to wait for notepad to start
                notepad.WaitForInputIdle();

                IntPtr p = notepad.MainWindowHandle;
                ShowWindow(p, 1);
                SendKeys.SendWait("ABC");
            }
    }
}

这篇关于如何将 F4 键发送到 C# 中的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆