3

Hi I'm trying to switch windows to other programs that are running (even if minimized) using C#.

I'm wondering why this won't work.

Error message: Argument 1: cannot convert from 'System.Diagnostics.Process' to 'System.IntPtr'

By the time it hits the loop I would think that the proc variable would refer to the appropriate window handler. Is this not true? I really appreciate the help.

//declarations
using system.IO;
using System.Runtime.InteropServices;
//more

//namespace here

//class here

//initialize method

//related .dll import
[DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd);

String ProcWindow = "itunes";
//function which calls switchWindow() is here but not important

//now we have switch window.
private void switchWindow()
        {
            Process[] procs = Process.GetProcessesByName(ProcWindow);
            foreach (Process proc in procs)
            {
                //switch to process by name
                SwitchToThisWindow(proc);

            }
        }

For future readers: I got to this point in my code from another question. Correct way (in .NET) to switch the focus to another application

Community
  • 1
  • 1
camdixon
  • 852
  • 2
  • 18
  • 33
  • The process object isn't the process handle (which an intptr). Look here: http://stackoverflow.com/questions/1276629/c-sharp-get-running-process-given-process-handle – jwrush Aug 21 '13 at 18:00

2 Answers2

5

SwitchToThisWindow is expecting a handle to the window that you want to switch to in that process.

Try

SwitchToThisWindow(proc.MainWindowHandle);
Doug Morrow
  • 1,306
  • 1
  • 10
  • 18
5

I believe what you want is:

[DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool turnon);

String ProcWindow = "itunes";
//function which calls switchWindow() is here but not important

//now we have switch window.
private void switchWindow()
{
  Process[] procs = Process.GetProcessesByName(ProcWindow);
  foreach (Process proc in procs)
  {
     //switch to process by name
     SwitchToThisWindow(proc.MainWindowHandle, false);

  }
}

SwitchToThisWindow expects an IntPtr that is a handle to a window, not a process which is what you were trying to pass in.

Also note that your pinvoke signature for SwitchToThisWindow appeared to be incorrect, you were missing the bool parameter.

chris.house.00
  • 3,273
  • 1
  • 27
  • 36
  • Boolean parameter should be false. http://msdn.microsoft.com/en-us/library/windows/desktop/ms633553%28v=vs.85%29.aspx – Sriram Sakthivel Aug 21 '13 at 18:08
  • 1
    Noted, I have updated it. Thanks for helping me improve my code. I appreciate the article too, so I can understand why it should be false. – camdixon Aug 21 '13 at 18:18
  • Another quick related question. How can I detect through the api if the window is open? If it is, then I will call this function – camdixon Aug 21 '13 at 18:46