Click here to Skip to main content
15,892,537 members
Home / Discussions / C#
   

C#

 
AnswerRe: Close Firefox with C# Pin
Rajesh R Subramanian13-Aug-09 22:42
professionalRajesh R Subramanian13-Aug-09 22:42 
GeneralRe: Close Firefox with C# Pin
nhqlbaislwfiikqraqnm13-Aug-09 22:51
nhqlbaislwfiikqraqnm13-Aug-09 22:51 
GeneralRe: Close Firefox with C# Pin
0x3c013-Aug-09 22:54
0x3c013-Aug-09 22:54 
GeneralRe: Close Firefox with C# Pin
nhqlbaislwfiikqraqnm13-Aug-09 22:59
nhqlbaislwfiikqraqnm13-Aug-09 22:59 
GeneralRe: Close Firefox with C# Pin
Eddy Vluggen13-Aug-09 23:14
professionalEddy Vluggen13-Aug-09 23:14 
GeneralRe: Close Firefox with C# Pin
nhqlbaislwfiikqraqnm13-Aug-09 23:41
nhqlbaislwfiikqraqnm13-Aug-09 23:41 
GeneralRe: Close Firefox with C# Pin
Eddy Vluggen13-Aug-09 23:55
professionalEddy Vluggen13-Aug-09 23:55 
GeneralRe: Close Firefox with C# Pin
Pete O'Hanlon14-Aug-09 1:10
mvePete O'Hanlon14-Aug-09 1:10 
Unfortunately, the solution you've got won't work in all cases; notably in applications that are running as multiple top level single instance applications. If you open up multiple instances of firefox and look in Task Manager, you'll see only one instance of FireFox there (i.e. one process). This is because FireFox is actually a single instance application with multiple top level windows (these are intended to save memory).

In order to kill all the instances, you'll need to resort to a bit of p/invoke trickery where you retrieve the window title of all the running windows, and then look for those windows that contain the string "Mozilla Firefox". When you find them, you close them via the API. The following code sample demonstrates this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace KillFirefox
{
  class Program
  {

    static void Main(string[] args)
    {
      KillWindowProcesses.KillProcess("Mozilla Firefox");
    }


    /// <summary>
    /// Certain window applications open up multiple top level windows, but only
    /// run as one process. This makes them difficult to kill using the standard
    /// <see cref="Process"/> methods. This class provides the ability to kill a
    /// process based on it's name.
    /// </summary>
    public class KillWindowProcesses
    {
      const int MAXTITLE = 255;
      const int WM_CLOSE = 0x0010;
      private static string name = string.Empty;

      private delegate bool EnumDelegate(IntPtr hWnd, int lParam);

      [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows",
       ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
      private static extern bool _EnumDesktopWindows(
        IntPtr hDesktop,
        EnumDelegate lpEnumCallbackFunction, 
        IntPtr lParam);

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

      // Used to post the close message
      [return: MarshalAs(UnmanagedType.Bool)]
      [DllImport("user32.dll", SetLastError = true)]
      static extern bool PostMessage(
        IntPtr hWnd, 
        uint Msg, IntPtr 
        wParam, IntPtr 
        lParam);

      public static void KillProcess(string processName)
      {
        name = processName;
        // Retrieve the list of processes.
        GetDesktopWindowsCaptions();
      }

      /// <summary>
      /// Call the PostMessage API.
      /// </summary>
      private static void PostMessageSafe(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
      {
        bool returnValue = PostMessage(hWnd, msg, wParam, lParam);
        if (!returnValue)
        {
          // An error occured
          throw new Win32Exception(Marshal.GetLastWin32Error());
        }
      }

      /// <summary>
      /// Callback method for the enumerate windows procedure.
      /// </summary>
      private static bool EnumWindowsProc(IntPtr hWnd, int lParam)
      {
        string title = GetWindowText(hWnd);
        if (!string.IsNullOrEmpty(title) && title.Contains(name))
        {
          PostMessageSafe(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        }
        return true;
      }

      /// <summary>
      /// Returns the caption of a windows by given HWND identifier.
      /// </summary>
      private static string GetWindowText(IntPtr hWnd)
      {
        StringBuilder title = new StringBuilder(MAXTITLE);
        int titleLength = _GetWindowText(hWnd, title, title.Capacity + 1);
        title.Length = titleLength;

        return title.ToString();
      }

      /// <summary>
      /// Returns the caption of all desktop windows.
      /// </summary>
      private static void GetDesktopWindowsCaptions()
      {
        EnumDelegate enumfunc = new EnumDelegate(EnumWindowsProc);
        IntPtr hDesktop = IntPtr.Zero; // current desktop
        bool success = _EnumDesktopWindows(hDesktop, enumfunc, IntPtr.Zero);

        if (!success)
        {
          // Get the last Win32 error code
          int errorCode = Marshal.GetLastWin32Error();

          string errorMessage = String.Format(
          "EnumDesktopWindows failed with code {0}.", errorCode);
          throw new Exception(errorMessage);
        }
      }
    }
  }
}


"WPF has many lovers. It's a veritable porn star!" - Josh Smith

As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.


My blog | My articles | MoXAML PowerToys | Onyx



GeneralRe: Close Firefox with C# Pin
0x3c014-Aug-09 1:31
0x3c014-Aug-09 1:31 
GeneralRe: Close Firefox with C# Pin
Pete O'Hanlon14-Aug-09 1:47
mvePete O'Hanlon14-Aug-09 1:47 
GeneralRe: Close Firefox with C# Pin
0x3c014-Aug-09 2:01
0x3c014-Aug-09 2:01 
GeneralRe: Close Firefox with C# Pin
Pete O'Hanlon14-Aug-09 2:28
mvePete O'Hanlon14-Aug-09 2:28 
GeneralRe: Close Firefox with C# Pin
PRMan!!!16-Oct-09 12:12
PRMan!!!16-Oct-09 12:12 
AnswerRe: Close Firefox with C# Pin
benjymous14-Aug-09 1:37
benjymous14-Aug-09 1:37 
GeneralRe: Close Firefox with C# Pin
nhqlbaislwfiikqraqnm15-Aug-09 10:24
nhqlbaislwfiikqraqnm15-Aug-09 10:24 
QuestionAForge.NET Pin
SP Vilakazi13-Aug-09 21:27
SP Vilakazi13-Aug-09 21:27 
AnswerRe: AForge.NET Pin
Pete O'Hanlon13-Aug-09 21:57
mvePete O'Hanlon13-Aug-09 21:57 
Questiontriggering the mouse click and hold event Pin
prasadbuddhika13-Aug-09 21:21
prasadbuddhika13-Aug-09 21:21 
AnswerRe: triggering the mouse click and hold event Pin
musefan13-Aug-09 21:52
musefan13-Aug-09 21:52 
AnswerRe: triggering the mouse click and hold event Pin
OriginalGriff13-Aug-09 21:54
mveOriginalGriff13-Aug-09 21:54 
QuestionHelp with Entity framework approach. Pin
SpiveyC#13-Aug-09 21:01
SpiveyC#13-Aug-09 21:01 
AnswerRe: Help with Entity framework approach. Pin
Henry Minute14-Aug-09 13:46
Henry Minute14-Aug-09 13:46 
GeneralRe: Help with Entity framework approach. Pin
SpiveyC#14-Aug-09 23:22
SpiveyC#14-Aug-09 23:22 
QuestionDynamically Loading Custom Control Pin
Matt Cavanagh13-Aug-09 20:46
Matt Cavanagh13-Aug-09 20:46 
AnswerRe: Dynamically Loading Custom Control Pin
SpiveyC#13-Aug-09 21:03
SpiveyC#13-Aug-09 21:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.