C#在.net中切换窗口

cam*_*xon 2 .net c# process dllimport

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

            }
        }
Run Code Online (Sandbox Code Playgroud)

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

Dou*_*row 5

SwitchToThisWindow期待一个需要您要在该过程中切换到的窗口句柄

尝试

SwitchToThisWindow(proc.MainWindowHandle);
Run Code Online (Sandbox Code Playgroud)


chr*_*.00 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);

  }
}
Run Code Online (Sandbox Code Playgroud)

SwitchToThisWindow期望一个IntPtr是一个窗口句柄,而不是你试图传入的进程.

另请注意,您的SwitchToThisWindow的pinvoke签名似乎不正确,您错过了bool参数.