3

您好我正在尝试使用 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);

            }
        }

对于未来的读者:我从另一个问题的代码中得到了这一点。 将焦点切换到另一个应用程序的正确方法(在 .NET 中)

4

2 回答 2

5

SwitchToThisWindow期望在该过程中要切换到的窗口的句柄。

尝试

SwitchToThisWindow(proc.MainWindowHandle);
于 2013-08-21T18:03:07.380 回答
5

我相信你想要的是:

[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,而不是您试图传入的进程。

另请注意,您对 SwitchToThisWindow 的 pinvoke 签名似乎不正确,您缺少 bool 参数。

于 2013-08-21T18:05:07.903 回答