如何将ctrl + c发送到活动进程? [英] How to send ctrl+c to active process?

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

问题描述

在Windows窗体应用程序中,我想将Ctrl + C发送到活动窗口,以便在按下Win + C时获取所选文本以进行翻译。



< b>我尝试了什么:



In Windows forms applications, I want to send Ctrl+C to active window to get the selected text to translate it when Win+C is pressed.

What I have tried:

                    Process p = Process.GetProcessesByName(GetActiveProcessFileName()).FirstOrDefault();
                    if (p != null)
                    {
                        IntPtr h = p.MainWindowHandle;
                        SetForegroundWindow(h);

                        SendKeys.SendWait("^C");

                    }




[DllImport("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);




[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);


static string GetActiveProcessFileName()
{
    IntPtr hwnd = GetForegroundWindow();
    uint pid;
    GetWindowThreadProcessId(hwnd, out pid);
    Process p = Process.GetProcessById((int)pid);
    return p.MainModule.FileName;
}

推荐答案

p 为空,因为 Process.GetProcessesByName 期望进程的友好名称,而不是GetActiveProcessFileName返回的完整文件路径。



但是这里有一些好消息:你甚至不需要使用GetProcessesByName来获得你想要的进程:在GetActiveProcessFileName中,你有一行进程p = Process.GetProcessById((int) pid)而这个 p 正是你想要的过程,所以你不需要返回这个进程的文件名来稍后再次检索进程:只需返回 p 。这是一个返回所需过程的 GetActiveProcess 方法:

p is null because Process.GetProcessesByName expects the "friendly name" of a process, not the full file path that appears to be returned by GetActiveProcessFileName.

But here's some good news: you don't even need to use GetProcessesByName to get the process you want: in GetActiveProcessFileName, you have a line Process p = Process.GetProcessById((int)pid) and this p is exactly the process you wish, so you don't need to return this process's file name to retrieve the Process again later: just return p already. Here is a GetActiveProcess method that returns the desired process:
static Process GetActiveProcess()
{
    IntPtr hwnd = GetForegroundWindow();
    uint pid;
    GetWindowThreadProcessId(hwnd, out pid);
    return Process.GetProcessById((int)pid);
}

然后你可以用这个替换 Process p = Process.GetProcessesByName ... 行:

And then you can replace the Process p = Process.GetProcessesByName ... line with this:

Process p = GetActiveProcess();









似乎^ C并不总是让活动应用程序复制选定的文本,但我用^得到了更好的结果^ c(即小写c)。





It appears that "^C" doesn't always make the active application copy the selected text, but I've had better results with "^c" (that is, a lowercase c).


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

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