【问题标题】:how to detect a new application being launched from C#?如何检测从 C# 启动的新应用程序?
【发布时间】:2011-03-11 10:32:32
【问题描述】:

我有一个用于 c# 的 .dll 库,它喜欢在启动时弹出一个“欢迎”屏幕。 此屏幕显示为任务管理器中的应用程序。

有没有办法自动检测这个应用程序/表单正在启动并关闭它?

谢谢! :)

【问题讨论】:

标签: c#


【解决方案1】:

如果它在您的进程中运行并打开一个表单(而不是对话框),您可以使用类似的方法来关闭您自己的程序集未打开的所有表单。

foreach (Form form in Application.OpenForms)
    if (form.GetType().Assembly != typeof(Program).Assembly)
        form.Close();

什么是您自己的程序集由类 Program 定义,您也可以使用 Assembly.GetExecutingAssemblyAssembly.GetCallingAssembly,但我不确定如果您在 Visual Studio 中运行应用程序(因为它可能会返回 VS 程序集)。

【讨论】:

  • 它工作!目前我将它连接到一个计时器上并制作 if (form.Text == "Welcome"){ form.Close();并且它关闭了。 :) 还有一件事,我如何检测到一个新表单正在打开,以便在创建表单时运行它,而不是通过计时器? :)
  • 在计时器上运行它并不漂亮,是的。您应该能够追踪表单打开的来源,然后直接关闭它。有可能获得callback on form opening,但我想我之前尝试过类似的方法,但没有成功。
【解决方案2】:

这里是一个简单的控制台应用程序,它将监视和关闭指定的窗口

class Program
{
    static void Main(string[] args)
    {
        while(true)
        {
            FindAndKill("Welcome");
            Thread.Sleep(1000);
        }
    }

    private static void FindAndKill(string caption)
    {
        Process[] processes = Process.GetProcesses();
        foreach (Process p in processes)
        {
            IntPtr pFoundWindow = p.MainWindowHandle;           
            StringBuilder windowText = new StringBuilder(256);

            GetWindowText(pFoundWindow, windowText, windowText.Capacity);
            if (windowText.ToString() == caption)
            {
                p.CloseMainWindow();
                Console.WriteLine("Excellent kill !!!");
            }
        }
    }

    [DllImport("user32.dll", EntryPoint = "GetWindowText",ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int GetWindowText(IntPtr hWnd,StringBuilder lpWindowText, int nMaxCount);
}

【讨论】:

  • Console.WriteLine("MMMMMMONSTER KILL!"); =P
  • MMMMMONSTER 杀了! :) * 竖起大拇指 *
  • 感谢代码,我去看看!顺便说一句,我应该添加 user32.dll 作为参考吗?
  • user32.dll 它是本机 Windows dll。你不能像参考一样添加它
  • 我认为这行不通,因为“欢迎”对话框很可能不是在自己的进程中运行,而是在您的进程中。
猜你喜欢
  • 2021-11-06
  • 2017-06-05
  • 1970-01-01
  • 1970-01-01
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 2013-10-01
相关资源
最近更新 更多