动态设置焦点到C#中的另一个程序

时间:2016-09-01 04:01:07

标签: c#

Visual Studio 2013有一个正在运行的过程。我想从桌面应用程序中关注它。我的代码 -

Process[] arrProcesses = Process.GetProcessesByName(strProcessName);
if (arrProcesses.Length > 0)
{
    IntPtr ipHwnd = arrProcesses[0].MainWindowHandle;
    Thread.Sleep(100);
    SetForegroundWindow(ipHwnd);
}

我尝试Microsoft Visual Studio 2013 (32 bit)Microsoft Visual Studio 2013Microsoft Visual Studio作为strProcessName。但它们都不起作用。

任何帮助?

2 个答案:

答案 0 :(得分:1)

    [DllImport("USER32.DLL")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("USER32.DLL")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);

    private void FindAppSetFocusAndSendKeyStrokes()
    {
        TryFindWindowAndSetFocus("ThunderRT6FormDC", "Human Resource Management System");
        SendKeyStrokes("%ML{ENTER}");
    }

    private void TryFindWindowAndSetFocus(string strClassName, string strCaption)//If you can't find strClassName, use String.Empty instead.
    {
        Thread.Sleep(1000);
        int intCounter = 0;
        IntPtr processHandler = FindWindow(strClassName, strCaption);

        while (processHandler == IntPtr.Zero)
        {
            if (intCounter > 9)
                break;

            Thread.Sleep(1000);
            processHandler = FindWindow(strClassName, strCaption);
            intCounter++;
        }
        if (processHandler == IntPtr.Zero)
            throw new Exception("Could not find the Process Window");

        intCounter = 0;
        while (!SetForegroundWindow(processHandler))
        {
            if (intCounter > 9)
                break;

            Thread.Sleep(500);
            intCounter++;
        }
        if (intCounter > 9)
            throw new Exception("Could not set Process foreground window");
    }
    private void SendKeyStrokes(string strKeys)
    {
        Thread.Sleep(100);
        SendKeys.SendWait(strKeys);
        SendKeys.Flush();
    }

答案 1 :(得分:1)

您可以添加对Microsoft.VisualBasic的引用并尝试AppActivate

Microsoft.VisualBasic.Interaction.AppActivate("Visual"); 

<强>更新

AppActivate只查找标题以title参数开头的主窗口(标题参数至少需要3个字符),但Visual Studio主窗口标题通常类似Solution Name - Microsoft Visual Studio,所以你可以使用解决方案名称或:

var processes = Process.GetProcessesByName("devenv");
if(processes.Any()) 
    Microsoft.VisualBasic.Interaction.AppActivate(processes[0].MainWindowTitle);