0

I have to bring an already opened window to the foreground and focus it to give inputs from my program. I list all running processes, select the one I need, and bring it foreground, but the problem is that this process has 3 windows. I need only one from the 3, but my solution brings all three in front. All three windows has a different name. Does anyone have any ideas? Maybe get the windows by name somehow?

Process[] processes = Process.GetProcessesByName(ProcessName);
if (processes.Length > 0)
{
    Process p = Process.GetCurrentProcess();
    int n = 0;  

    if (processes[0].Id == p.Id)
    {
        n = 1;
    }

    IntPtr hWnd = processes[n].MainWindowHandle;

    if (IsIconic(hWnd))
    {
         ShowWindowAsync(hWnd, SW_RESTORE);
    }

    SetForegroundWindow(hWnd);
TIS
  • 1
  • This goes into Desktop Automation/General Automation. There are dedicated tools for those things. In general it is one of those things that are possible, but will require leaving managed code to call some Windows API, deal with Windows Handles, etc. Right now oyu code does some wierd stuff. Like if Process[0] is the right one, it tries to access Process[1]? I think you are missing some for loop in there to find the right process. – Christopher Apr 15 '18 at 04:54
  • Basically I found this code on internet, and it is working, but not as I need it. It brings the window of the selected process to front. The if sentence you mentioned is required if there are more processes with the same name, but it can be deleted as there will be only one process in my case. My problem is that the selected process has 3 different windows. I need to bring the right one and activate the cursor in it. This is needed as there are no other method to pass my data to the program – TIS Apr 15 '18 at 05:21
  • Your first choice of option should be following Douglas Adams adivce: Take away that original programm out of the picture and learn to live without it. Even just reverse engineering a replacement that you have a decent amount of control over. When all that fails, there is this way: https://stackoverflow.com/questions/79111/net-c-getting-child-windows-when-you-only-have-a-process-handle-or-pid But as I said, you need to use the Windows API and that means unamanged code. So it gives you all those headaches (binarity, handling naked pointers) the .NET Designers wanted to shield you from. – Christopher Apr 15 '18 at 14:22

0 Answers0