检查进程是否正在运行。如果是的话 - 打开它

问题描述 投票:0回答:2

好吧,让我说我有一个process运行。

可以说,“Skype”。我想点击C#Windows Form App中的button

当我点击button(让我们称之为button“Skype Run”)。

所以,当我点击“Skype Run”时。它将检查进程当前是否正在运行。

如果进程没有运行,可以说它会:

MessageBox.Show("Sorry! Skype is not running.")

但。如果它正在运行,它将打开它作为你正在看的窗口。

所以,如果你在Word中,并点击“Skype Run”。 Skype正在运行,它打开了窗口。 (就像在Windows中的任务管理器中执行“切换到”一样。)

如果我没有很好地解释我的问题,请告诉我。我真的需要答案:)

c# windows winforms
2个回答
3
投票

这里有一个代码示例,说明了如何执行此操作:

http://www.codeguru.com/forum/showthread.php?p=1757526

以下帖子中的相关代码示例。这显示了如何在button1_Click事件处理程序中查找进程。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices; //required for APIs
namespace Find

{

public partial class Form1 : Form
{
    //Import the FindWindow API to find our window
    [DllImportAttribute("User32.dll")]
    private static extern int FindWindow(String ClassName, String WindowName);

    //Import the SetForeground API to activate it
    [DllImportAttribute("User32.dll")]
    private static extern IntPtr SetForegroundWindow(int hWnd);


    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Find the window, using the CORRECT Window Title, for example, Notepad
        int hWnd = FindWindow(null, "Untitled - Notepad");
        if (hWnd > 0) //If found
        {
            SetForegroundWindow(hWnd); //Activate it
        }
        else
        {
            MessageBox.Show("Window Not Found!");
        }


    }
}
}

1
投票

您可以使用Process.GetProcessesByName静态方法检查进程是否已在运行。

使用SetWindowPos Win API可以实现前面的特定窗口

© www.soinside.com 2019 - 2024. All rights reserved.