如何使用Win32 API在WinForm前显示System.Diagnostics

时间:2012-10-19 02:58:02

标签: c# winforms process win32gui

在我的主窗体上,我有一个ListView,其中包含LargeIcon属于我们软件套件的进程视图中的列表。每个LV(ListView)项目都包含文本和图像,这些图像与我们用于相应应用程序的软件产品的图标(即MarinaOffice,LaunchOffice,PureRental等等)相同。有一个计时器根据是否在Process.GetProcesses()方法调用中找到该进程来更新列表。当用户单击正在运行的进程的ListView项时,它应该最大化并在当前进程前显示该进程的窗口(即WinForms Application)。下面的代码几乎完成了我想要完成的任务,但是,在我想要显示的应用程序已经最大化的情况下,但是,我在监视器上的Windows应用程序后面,它没有把我正在显示的进程放在前面我的申请换句话说,只要我使用下面的WIN32方法显示的应用程序被最小化,它就可以工作。但是,它已经最大化了,它没有。

// Used to Show Other Process Windows
private const int SW_SHOWMAXIMIZED = 3;
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);    

// Method that checks for running apps in our suite every 3000ms
private void timerRunningApps_Tick(object sender, EventArgs e)
{
    CheckRunningapps();
}

// Stripped down version of method that looks for running process in our suite and 
// adds the process name and icon to a ListView on our main form
private void CheckRunningapps()
{
    List<Process> AllProcesses = System.Diagnostics.Process.GetProcesses().ToList();

    listViewRunningApps.BeginUpdate();
    listViewRunningApps.Items.Clear();

    foreach (Process process in AllProcesses)
    {
        ListViewItem lvi = new ListViewItem();
        if (process.ProcessName.ToLower().Contains("marinaoffice"))
        {
            lvi = new ListViewItem("MarinaOffice");
            lvi.SubItems.Add("MarinaOffice");
            lvi.ImageIndex = 1;
            lvi.Tag = process;
            listViewRunningApps.Items.Add(lvi);
        }
    }

    listViewRunningApps.EndUpdate();
}

// Method that actually shows the process.  This works as long as process is minimized
// However, if the process is maximized but, merely behind the current window it does
// not bring it in front.  I have noticed that there is a ShowWindowAsync method.
// Should I use that instead?
private void listViewRunningApps_MouseDoubleClick(object sender, MouseEventArgs e)
{
    ListViewItem lvi = listViewRunningApps.GetItemAt(e.X, e.Y);
    if (lvi != null)
    {
        Process process = (Process)lvi.Tag;
        ShowWindow(process.MainWindowHandle, SW_SHOWMAXIMIZED);
    }
}

1 个答案:

答案 0 :(得分:1)

尝试类似这样的事情,我认为发生的事情是你没有用ShowWindow调用改变Window状态如果Window已经最大化,那么你需要将它带到Z-Order的前面使用BringWindowToTop方法。

Process process = (Process)lvi.Tag; 
ShowWindow(process.MainWindowHandle, SW_SHOWMAXIMIZED);
BringWindowToTop(process.MainWindowHandle);