在c#中动态地将焦点设置为另一个程序

本文关键字:设置 另一个 程序 焦点 动态 | 更新日期: 2023-09-27 18:04:57

有一个正在运行的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 2013, Microsoft Visual Studio作为strProcessName。

帮忙吗?

在c#中动态地将焦点设置为另一个程序

您可以将引用添加到Microsoft.VisualBasic并尝试AppActivate

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

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

var processes = Process.GetProcessesByName("devenv");
if(processes.Any()) 
    Microsoft.VisualBasic.Interaction.AppActivate(processes[0].MainWindowTitle); 
    [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();
    }