How to Bring an application to front with C#

  • Thread starter Thread starter zydjohn
  • Start date Start date
Z

zydjohn

Guest
Hello:

I have a C# Console Project using Puppeteer Sharp to grab some web pages. But from time to time, when I browse internet, web browsers are in front. As the web browsers hide Puppeteer Sharp window, then some actions, like the URL detect and click are affected, therefore, they don’t work from time to time, but if I keep the Puppeteer Sharp window (showing the Chromium page) in front, then usually, the Puppeteer Sharp program works.

Therefore, I guess if I can write another program, can always bring the Puppeteer Sharp window to the front, then I don’t have to do this by hand.

I searched around, and I got some code, like the following: (.Net Core Console Project with C# 7.3)



using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace AppToFront
{
class Program
{
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

static void Main()
{
//Checks if application is running
try
{
Process process = Process.GetProcessesByName("Chromium")[0];
if (process != null)
{
process.WaitForInputIdle();
IntPtr s = process.MainWindowHandle;
SetForegroundWindow(s);
Console.Write("Proccess found: " + process.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR: Application is not running!\nException: " + ex.Message);
Console.ReadKey();
return;
}
}
}
}


But when I run the program.

I always got the following result:

ERROR: Application is not running!

Exception: Index was outside the bounds of the array.


C:\Program Files\dotnet\dotnet.exe (process 16720) exited with code -1.

To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.

Press any key to close this window . . .


Even I can see from Task Manager that there are always at least 2 Chromium processes are running, but my program can’t detect any of them. But if I change the statement:

Process process = Process.GetProcessesByName("Chromium")[0];

To anther one, like this:

Process process = Process.GetProcessesByName("Chrome")[0];

I can always get the result if I open Google Chrome browser in my PC. But Chrome is not the window I want to bring to front. I want to get the Chromium window, but my code is not working.

Any advice?

By the way, as it is already 2019, are there any way to do the same job without using Windows API?

My PC is running Windows 10 (Version 1903) and I am use Visual Studio 2019 (Version 16.1.6).

Thanks,

Continue reading...
 
Back
Top