2

I have a .dll library for c# that loves to pop out a 'Welcome' screen when it starts. This screen appears as an application in the task manager.

Is there some way to automatically detect this application/form being launched and close it?

Thanks! :)

Roger
  • 6,443
  • 20
  • 61
  • 88
  • Possible duplicate to http://stackoverflow.com/questions/848618/net-events-for-process-executable-start – Terry Mar 11 '11 at 10:35

2 Answers2

4

Here us simple console application that will monitor and close specified window

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);
}
Stecya
  • 22,896
  • 10
  • 72
  • 102
3

If it's running within your process and opening a Form (not a Dialog), you can use something like this to close all Forms which aren't opened by your own Assembly.

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

What is your own Assembly is defined by the class Program, you could also use Assembly.GetExecutingAssembly or Assembly.GetCallingAssembly, but I'm not sure it will behave correctly, if you run the Application inside Visual Studio (since it might return the VS Assembly).

xod
  • 589
  • 3
  • 5
  • IT WORKS! Currently I hooked it onto a timer and made if (form.Text == "Welcome"){ form.Close(); } and it closes ok. :) Just one more thing, how do I detect that a new form is being open, so that I would run this when a form is created, no by timer? :) – Roger Mar 11 '11 at 11:14
  • Running this on a timer is not pretty, yes. You should be able to track down the source of the form opening and just close it directly afterwards. There could be possibilities of getting a [callback on form opening](http://stackoverflow.com/questions/1603600/winforms-is-there-a-way-to-be-informed-whenever-a-form-gets-opened-in-my-applica), but I think i tried something like that before and it didn't work. – xod Mar 11 '11 at 12:09