0

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

Community
  • 1
  • 1
Rhys
  • 1
  • 1
  • 8
  • Try using `MainWindowHandle` instead of `Handle`? – King King Sep 14 '13 at 11:23
  • that doesnt work eather, the handle returns 0 `var proc = Process.GetProcessesByName("chrome")[0].MainWindowHandle; Console.WriteLine(proc.ToString());` – Rhys Sep 14 '13 at 11:38
  • 1
    It is *definitely* not going to work if you use a process id where a window handle is required. SetForegroundWindow() just isn't guaranteed to work at all, you cannot shove a window into the user's face. There's a dirty trick around it, also available in the .NET framework. Use the Microsoft.VisualBasic.Interaction.AppActivate() method. It takes the process id. – Hans Passant Sep 14 '13 at 11:39
  • ok.. so as the rest of my program is written in c# what do i do? – Rhys Sep 14 '13 at 11:44
  • so . handle isnt the window handle? its the id... so whats .Id? – Rhys Sep 14 '13 at 11:47
  • i found this, unfortnatly i cant quite make heads or tails of it, is it gunna work? http://www.vbforums.com/showthread.php?356070-ShowWindow-can-t-bring-to-front-Resolved-D&highlight=activate – Rhys Sep 14 '13 at 16:14

0 Answers0