我用C#写了一个最小化到托盘的程序,并使它单实例运行,运行第二个实例时,恢复第一个实例的窗口,并置于最前。
当第一个实例最小化时,调用自己的方法可以正常恢复窗口,运行第二个实例时,可以恢复窗口,但只有之前激活的TabPage中可以正常显示内容,其他TabPage中全部是空白。代码如下,希望大虾指点。
P.s. 查了一些资料,貌似被隐藏的窗体不能用instance.MainWindowHandle获得句柄,而根据窗体名字获得句柄的方法似乎有些问题,但不知如何解决
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
private const int WS_SHOWNORMAL = 1;
public const Int32 AW_BLEND = 0x00080000;
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll")]
private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process instance = RunningInstance();
if (instance == null)
{
Application.Run(new Form1());
}
else
{
HandleRunningInstance(instance);
}
}
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
return process;
}
}
}
return null;
}
public static void HandleRunningInstance(Process instance)
{
if (instance.MainWindowHandle.ToInt32() != 0)
{
ShowWindowAsync(instance.MainWindowHandle, 9);
SetForegroundWindow(instance.MainWindowHandle);
}
else
{
IntPtr hwnd = FindWindow(null, "窗体名字");
ShowWindowAsync(hwnd, 9);
SetForegroundWindow(hwnd);
}
}
}