我正在编写一个C#程序,在其中我使用ShowWindow来显示或隐藏其他进程的窗口。我的问题是,如果在程序运行之前窗口已经隐藏,我无法使用我的程序来显示或隐藏进程窗口。
例如,如果我要运行我的程序,隐藏其他进程的窗口,然后显示它,它将正常工作。但是,如果我要运行我的程序,隐藏其他进程的窗口,终止我的程序,然后再次运行我的程序,我将无法再显示该进程的窗口。
我希望能够显示隐藏进程的窗口,即使它们在程序运行之前是隐藏的。我怎样才能做到这一点?
Program.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 2)
{
if (args[0] == "showh")
{
int handle;
int.TryParse(args[1], out handle);
App.ShowHandle(handle);
}
else
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
App app = new App(process);
if (args[1] == app.Name)
{
if (args[0] == "show")
{
app.Show();
}
else
{
app.Hide();
}
}
}
}
}
}
}
}App.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class App
{
[DllImport("User32")]
private static extern int ShowWindow(int hwnd, int nCmdShow);
private const int SW_HIDE = 0;
private const int SW_SHOW = 5;
public String Name { get; private set; }
private Process process { get; set; }
public App(Process process)
{
this.Name = process.ProcessName;
this.process = process;
}
public void Hide()
{
int windowHandle = this.process.MainWindowHandle.ToInt32();
Console.WriteLine("Hiding {0}: has window handle {1}", this.Name, windowHandle);
ShowWindow(windowHandle, SW_HIDE);
}
public void Show()
{
int windowHandle = this.process.MainWindowHandle.ToInt32();
Console.WriteLine("Showing {0}: has window handle {1}", this.Name, windowHandle);
ShowWindow(windowHandle, SW_SHOW);
}
public static void ShowHandle(int handle)
{
Console.WriteLine("Showing window handle {0}", handle);
ShowWindow(handle, SW_SHOW);
}
}
}更新1:添加了最小和完整的代码示例。
更新2:经过进一步的实验,大多数进程实际上给了我一个零的窗口句柄。然而,在罕见的情况下,我得到一个非零窗口句柄,但窗口句柄是不正确的.
不正确,如:当进程被隐藏时,句柄值与我试图显示该进程时的句柄值不同。
但是,如果我记得进程的窗口句柄是隐藏的,我可以再次显示窗口,不管如何。我已经更新了我的代码示例以反映这一点。
然后,我的问题变成:如果进程是隐藏的,为什么我无法获得进程的正确窗口句柄?(但是,如果进程是可见的,然后是隐藏的,我就能够获得窗口句柄。)
发布于 2015-05-03 01:22:00
由于我没有收到任何答复,我想出了以下解决办法:
记住进程的窗口句柄,并将其与进程ID相关联。将其保存到文件中。当我的应用程序重新启动时,从文件中读取。现在我可以使用这些保存的窗口句柄来显示关联进程ID的隐藏窗口。
我也可以使用这个id返回process对象。
Process proc = Process.GetProcessById(processID);此外,一旦窗口显示,我再次能够获得窗口句柄
int windowHandle = this.process.MainWindowHandle.ToInt32();如果有人有更好的解决方案,请评论。然而,这是我现在要用的解决办法。
https://stackoverflow.com/questions/29872435
复制相似问题