C#在.net中切换窗口

C#在.net中切换窗口,c#,.net,process,dllimport,C#,.net,Process,Dllimport,嗨,我正在尝试将windows切换到使用C#运行(即使最小化)的其他程序 我想知道为什么这行不通 错误消息: 参数1:无法从“System.Diagnostics.Process”转换为“System.IntPtr” 当它到达循环时,我认为proc变量将引用适当的窗口处理程序。这不是真的吗? 我真的很感谢你的帮助 //declarations using system.IO; using System.Runtime.InteropServices; //more //namespace he

嗨,我正在尝试将windows切换到使用C#运行(即使最小化)的其他程序

我想知道为什么这行不通

错误消息: 参数1:无法从“System.Diagnostics.Process”转换为“System.IntPtr”

当它到达循环时,我认为proc变量将引用适当的窗口处理程序。这不是真的吗? 我真的很感谢你的帮助

//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);

            }
        }
未来读者: 我在代码中从另一个问题得到了这一点。

切换到此窗口希望在该过程中切换到的窗口有一个句柄

试一试


我相信你想要的是:

[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需要一个IntPtr,它是窗口的句柄,而不是您试图传递的进程


还要注意,您的pinvoke SwitchToThis窗口签名似乎不正确,您缺少bool参数。

进程对象不是进程句柄(它是intptr)。看这里:太棒了,所以它有我可以访问的属性。通过执行proc,你还能得到什么。?有关于它的好文章吗?当然,MSDN将永远是您最好的资源:布尔参数应该为false。注意,我已经更新了它。谢谢你帮助我改进代码。我也很欣赏这篇文章,所以我能理解为什么它应该是假的。另一个快速相关的问题。如何通过api检测窗口是否打开?如果是,那么我将调用此函数
[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);

  }
}