Advertisement
Guest User

Window Class

a guest
Jan 14th, 2011
537
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7.  
  8. namespace TomLib.WinApi
  9. {
  10.     /// <summary>
  11.     /// Models a Windows API window and acts as a wrapper for many unmanaged methods.
  12.     /// </summary>
  13.     public class Window
  14.     {
  15.         #region Windows API P/Invokes
  16.  
  17.         [DllImport("user32.dll", SetLastError = true)]
  18.         private static extern int GetWindowTextLength(IntPtr hWnd);
  19.  
  20.         [DllImport("user32.dll", SetLastError = true)]
  21.         private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
  22.  
  23.         [DllImport("user32.dll", SetLastError = true)]
  24.         [return: MarshalAs(UnmanagedType.Bool)]
  25.         private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
  26.  
  27.         [DllImport("user32.dll", SetLastError = true)]
  28.         [return: MarshalAs(UnmanagedType.Bool)]
  29.         private static extern bool CloseWindow(IntPtr hWnd);
  30.  
  31.         [DllImport("user32.dll", SetLastError = false)]
  32.         private static extern IntPtr GetDesktopWindow();
  33.  
  34.         [DllImport("user32.dll")]
  35.         [return: MarshalAs(UnmanagedType.Bool)]
  36.         private static extern bool IsWindowVisible(IntPtr hWnd);
  37.  
  38.         [DllImport("user32.dll")]
  39.         [return: MarshalAs(UnmanagedType.Bool)]
  40.         private static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
  41.  
  42.         [DllImport("user32.dll", SetLastError = true)]
  43.         private static extern int GetWindowLong(IntPtr hWnd, GetWindowLongNIndex nIndex);
  44.  
  45.         [DllImport("user32.dll", SetLastError = true)]
  46.         private static extern IntPtr FindWindow(IntPtr lpClassName, string lpWindowName);
  47.  
  48.         [DllImport("user32.dll")]
  49.         [return: MarshalAs(UnmanagedType.Bool)]
  50.         private static extern bool SetForegroundWindow(IntPtr hWnd);
  51.  
  52.         [DllImport("user32.dll")]
  53.         private static extern IntPtr GetForegroundWindow();
  54.  
  55.         [DllImport("user32.dll")]
  56.         private static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId);
  57.  
  58.         #endregion
  59.  
  60.         private readonly IntPtr _handle;
  61.  
  62.         /// <summary>
  63.         /// Initialise a new Window instance from a window handle. Window objects are thread-safe.
  64.         /// </summary>
  65.         /// <param name="handle">An <see cref="IntPtr"/> which identifies the window.</param>
  66.         public Window(IntPtr handle)
  67.         {
  68.             _handle = handle;
  69.         }
  70.  
  71.         /// <summary>
  72.         /// Initialise a new Window instance from the case-insensitive title of a top-level window.
  73.         /// </summary>
  74.         /// <param name="title">The title of the window.</param>
  75.         public Window(string title)
  76.         {
  77.             IntPtr foundHandle = FindWindow(IntPtr.Zero, title);
  78.             if (foundHandle.Equals(IntPtr.Zero))
  79.             {
  80.                 throw new ArgumentException("Could not find a window with a title matching: " + title, "title");
  81.             }
  82.             _handle = foundHandle;
  83.         }
  84.  
  85.         /// <summary>
  86.         /// Get a pointer to the window.
  87.         /// </summary>
  88.         public IntPtr Handle
  89.         {
  90.             get { return _handle; }
  91.         }
  92.  
  93.         /// <summary>
  94.         /// Get the text which is found in the window's title bar.
  95.         /// </summary>
  96.         public string Title
  97.         {
  98.             get
  99.             {
  100.                 int length = GetWindowTextLength(Handle);
  101.                 var title = new StringBuilder(length + 1);
  102.                 GetWindowText(Handle, title, title.Capacity);
  103.                 return title.ToString();
  104.             }
  105.         }
  106.  
  107.         /// <summary>
  108.         /// Get a boolean value indicating whether the window is visible or not.
  109.         /// </summary>
  110.         public bool IsVisible
  111.         {
  112.             get { return IsWindowVisible(Handle); }
  113.         }
  114.  
  115.         /// <summary>
  116.         /// Get an enumeration of all windows belonging to this window.
  117.         /// </summary>
  118.         public IEnumerable<Window> ChildWindows
  119.         {
  120.             get
  121.             {
  122.                 var childWindowsTemp = new List<Window>();
  123.                 var callbackPointer = new EnumWindowsProc((hWnd, lParam) =>
  124.                                                               {
  125.                                                                   childWindowsTemp.Add(new Window(hWnd));
  126.                                                                   return true;
  127.                                                               });
  128.                 EnumChildWindows(Handle, callbackPointer, (IntPtr) 0);
  129.                 return childWindowsTemp;
  130.             }
  131.         }
  132.  
  133.         /// <summary>
  134.         /// Get the flags representing the combination of window styles.
  135.         /// </summary>
  136.         public WindowStyleExtended StyleFlags
  137.         {
  138.             get
  139.             {
  140.                 int numericFlags = GetWindowLong(Handle, GetWindowLongNIndex.GWL_EXSTYLE);
  141.                 return (WindowStyleExtended) Enum.Parse(typeof (WindowStyleExtended), numericFlags.ToString());
  142.             }
  143.         }
  144.  
  145.         /// <summary>
  146.         /// Get the <see cref="System.Diagnostics.Process"/> which created the Window.
  147.         /// </summary>
  148.         public Process ParentProcess
  149.         {
  150.             get
  151.             {
  152.                 IntPtr processId;
  153.                 GetWindowThreadProcessId(Handle, out processId);
  154.                 return Process.GetProcessById(processId.ToInt32());
  155.             }
  156.         }
  157.  
  158.         /// <summary>
  159.         /// Get an enumeration of all windows.
  160.         /// </summary>
  161.         public static IEnumerable<Window> AllWindows
  162.         {
  163.             get
  164.             {
  165.                 var openWindowsTemp = new List<Window>();
  166.                 var callbackPointer = new EnumWindowsProc((hWnd, lParam) =>
  167.                                                               {
  168.                                                                   openWindowsTemp.Add(new Window(hWnd));
  169.                                                                   return true;
  170.                                                               });
  171.                 EnumWindows(callbackPointer, (IntPtr) 0);
  172.                 return openWindowsTemp;
  173.             }
  174.         }
  175.  
  176.         /// <summary>
  177.         /// Get the desktop window.
  178.         /// </summary>
  179.         public static Window DesktopWindow
  180.         {
  181.             get { return new Window(GetDesktopWindow()); }
  182.         }
  183.  
  184.         /// <summary>
  185.         /// Get an enumeration of all the windows which appear in the taskbar.
  186.         /// </summary>
  187.         public static IEnumerable<Window> TaskbarWindows
  188.         {
  189.             get { return DesktopWindow.ChildWindows.Where(window => window.StyleFlags.HasFlag(WindowStyleExtended.WS_EX_APPWINDOW)).ToList(); }
  190.         }
  191.  
  192.         /// <summary>
  193.         /// Get or set the foreground window.
  194.         /// </summary>
  195.         public static Window ForegroundWindow
  196.         {
  197.             get { return new Window(GetForegroundWindow()); }
  198.             set
  199.             {
  200.                 bool successful = SetForegroundWindow(value.Handle);
  201.                 if (!successful)
  202.                 {
  203.                     throw new WinApiException("Could not set foreground window.");
  204.                 }
  205.             }
  206.         }
  207.  
  208.         /// <summary>
  209.         /// Minimise but do not destroy the window.
  210.         /// </summary>
  211.         public void Minimise()
  212.         {
  213.             CloseWindow(Handle);
  214.         }
  215.  
  216.         /// <summary>
  217.         /// Checks for the existence of any window whose title matches a given string (case-sensitive).
  218.         /// </summary>
  219.         /// <param name="title">The string to match.</param>
  220.         /// <returns><c>true</c> or <c>false</c>, depending on whether a window with a matching title exists.</returns>
  221.         public static bool Exists(string title)
  222.         {
  223.             return AllWindows.Any(window => window.Title == title);
  224.         }
  225.  
  226.         // The definition of the method signature used for callback when enumerating windows.
  227.         private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
  228.     }
  229. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement