Changing the Window Focus c# user32.dll (SetForegroundWindow)

3.2k Views Asked by At

oh i have been trying to make a program which looks to see if a program in this case chrome is running then switching to it, i have been trying to follow a similar thread (thread one, thread two) unfortunately I'm having issues with the handle as it seems to like switching to windows explorer (file manager)

[DllImport("User32.dll")] 
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  
[DllImport("User32.dll")] 
static extern int SetForegroundWindow(IntPtr hWnd);

IntPtr ptrFF = FindWindow(null, "chrome");
SetForegroundWindow(ptrFF);

Process proc = Process.GetProcessesByName("firefox")[0];
IntPtr ptrFF = proc.Handle;
SetForegroundWindow(ptrFF);

these are the two bits of code i have been playing with, however i only got the second one to actuly do somthing, using a basic console aplication i tested weather it was actuly finding the right prosess when i uses "chrome" as the name and this appeared to be the case test code:

   var proc = Process.GetProcessesByName("chrome")[0];
   Console.WriteLine(proc.ToString());

The Output of the Writeline is "System.Diagnostics.Prosess (chrome)" if i printed Process.GetProcessesByName("chrome")[0].Handle; it comes out as 572

but using:

var proc = Process.GetProcessesByName("chrome")[0].Handle;
Console.WriteLine(proc.ToString());
SetForegroundWindow(proc);

doesn't set the current window to chrome nor give me any errors

0

There are 0 best solutions below