using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Diagnostics; using diag = System.Diagnostics; using System.Windows.Forms; using System.Runtime.InteropServices; using SysIO = System.IO; using Diag = System.Diagnostics; using Yaulw.Tools; namespace Yaulw.Win32 { /// /// Common Win32 .Net Wrapper Functions around Win32 for easier consumption by C# /// public static class Functions { #region Byte / Word /// /// Returns the Low word of the specified int /// /// int to retrieve low word from /// low word of the int public static int LOWORD(int n) { return (n & 0xffff); } /// /// Returns the Low byte of the specified int /// /// int to retrieve low byte from /// low byte of the int public static int LOBYTE(int n) { return (n & 0xff); } /// /// Returns the High word of the specified int /// /// int to retrieve high word from /// high word of the int public static int HIWORD(int n) { return ((n >> 16) & 0xffff); } /// /// Returns the High byte of the specified int /// /// int to retrieve high byte from /// high byte of the int public static int HIBYTE(int n) { return ((n >> 8) & 0xff); } #endregion #region RGB /// /// Win32 RGB /// /// red value as int /// green value as int /// blue value as int /// returns a Win32 RGB Value as int public static int RGB(int r, int g, int b) { int rs = r & 0xffff; int gs = (g << 8) & 0xffff; int bs = (b << 16) & 0xffff; return (rs | gs | bs); } /// /// Retrieve the Red Value from Win32 RGB Value /// /// /// returns Red value public static int GetRValue(int rgbDWORD) { return LOBYTE(rgbDWORD); } /// /// Retrieve the Green Value from Win32 RGB Value /// /// /// returns Green value public static int GetGValue(int rgbDWORD) { return (LOBYTE(rgbDWORD >> 8)); } /// /// Retrieve the Blue Value from Win32 RGB Value /// /// /// returns Blue value public static int GetBValue(int rgbDWORD) { return (LOBYTE(rgbDWORD >> 16)); } #endregion #region Keyboard Functionallity /// /// Use this Function to determine whether the user is holding down a specified key /// /// VK such as Ctrl/Alt/Shift /// true if pressed down, false otherwise public static bool IsKeyPressed(Definitions.VK vKey) { short retVal = User32.GetKeyState(vKey); return (retVal < 0); } #endregion #region ClientRect Functionallity /// /// Get a windows client rectangle /// /// A Window Handle /// A Rectangle public static Rectangle GetClientRect(IntPtr hWnd) { Structures.RECT rect = new Structures.RECT(); User32.GetClientRect(hWnd, out rect); return Convert.RECTToRectangle(rect); } /// /// Get a windows rectangle /// /// The Window handle /// A Rectangle public static Rectangle GetWindowRect(IntPtr hWnd) { Structures.RECT rect = new Structures.RECT(); User32.GetWindowRect(hWnd, out rect); return Convert.RECTToRectangle(rect); } /// /// Returns the Client Size, taking into account the Chrome width /// /// A Window Handle /// A Rectangle public static Rectangle GetAbsoluteClientRect(IntPtr hWnd) { Rectangle windowRect = GetWindowRect(hWnd); Rectangle clientRect = GetClientRect(hWnd); int chromeWidth = (int)((windowRect.Width - clientRect.Width) / 2); return new Rectangle(new Point(windowRect.X + chromeWidth, windowRect.Y + (windowRect.Height - clientRect.Height - chromeWidth)), clientRect.Size); } #endregion #region Window Functionallity /// /// Use this to get the name of a Window Class /// /// A Window Handle /// The name of the Window Class public static string GetWindowClassName(IntPtr hWnd) { StringBuilder ClassName = new StringBuilder(100); int nRet = User32.GetClassName(hWnd, ClassName, ClassName.Capacity); return ClassName.ToString(); } /// /// Use this to get the text of a Window /// /// A Window Handle /// The window Text public static string GetWindowText(IntPtr hWnd) { int length = User32.GetWindowTextLength(hWnd); StringBuilder sb = new StringBuilder(length + 1); User32.GetWindowText(hWnd, sb, sb.Capacity); return sb.ToString(); } /// /// Get the Window Text of a Dialog Item /// /// handle to Dialog /// uint Dialog Item /// Window Text from the Dialog Item public static string GetDlgItemText(IntPtr hDlg, int nIDDlgItem) { // Get the handle of the dialog item IntPtr hItem = User32.GetDlgItem(hDlg, nIDDlgItem); if (hItem == IntPtr.Zero) return String.Empty; return GetWindowText(hItem); } /// /// Use this to retrieve the Process Object for a specific Window Handle /// /// A Window Handle /// A valid Process object or Null if error occured public static System.Diagnostics.Process GetProcessFromWindowHandle(IntPtr hWnd) { int findPID = 0; User32.GetWindowThreadProcessId(hWnd, ref findPID); System.Diagnostics.Process process = null; try { if (findPID > 0) process = System.Diagnostics.Process.GetProcessById(findPID); } catch (ArgumentException) { /* ignore */ } return process; } /// /// Find the first top level window for the specified process /// /// Process ID /// the hWnd for the first Window of the specifed or IntPtr.Zero if none found public static IntPtr GetFirstTopLevelWindowForProcess(int pid) { IntPtr Result = IntPtr.Zero; // Enumerate the top-level windows User32.EnumWindowsProc proc = delegate(IntPtr hWnd, IntPtr lParam) { // Find the first Window that belongs to the specified Process if (User32.IsWindowVisible(hWnd) && (pid == GetProcessFromWindowHandle(hWnd).Id)) { Result = hWnd; return false; } return true; // Keep Looking }; User32.EnumWindows(proc, IntPtr.Zero); // yippie return Result; } /// /// /// /// /// public static IntPtr GetTopLevelChildWindowForProcess(int pid) { // To Do return IntPtr.Zero; } #endregion #region Desktop Window Functionallity /// /// Get's the Desktop Window as a Win32Window Object /// /// a Win32Window Object public static IWin32Window GetDestopWindow() { return Convert.ConverthWndToIWin32Window(User32.GetDesktopWindow()); } /// /// Refreshes orphaned Icons in the Taskbar /// /// /// public static void RefreshTaskbarNotificationArea() { // Find the Notification Area IntPtr hNotificationArea = IntPtr.Zero; hNotificationArea = User32.FindWindowEx (User32.FW(User32.FW(User32.FW(IntPtr.Zero, "Shell_TrayWnd"), "TrayNotifyWnd"), "SysPager"), IntPtr.Zero, "ToolbarWindow32", "Notification Area"); if (hNotificationArea == IntPtr.Zero || !User32.IsWindow(hNotificationArea)) return; // Get the Client Rect of the Notification Area Structures.RECT r; User32.GetClientRect(hNotificationArea, out r); // Send Mouse Messages to the Notification Area for (int x = 0; x < r.right; x += 5) for (int y = 0; y < r.bottom; y += 5) User32.SendMessage(hNotificationArea, (int) Definitions.WM.WM_MOUSEMOVE, (IntPtr) 0, (IntPtr) ((y << 16) + x)); } #endregion #region Process Kernel Functionallity // SetProcessDEPPolicy Helpers private delegate bool SetProcessDEPPolicy_Delegate(int dwFlags); private static SetProcessDEPPolicy_Delegate SetProcessPolicy = null; /// /// Use SetProcessDEPPolicy to set the DEP Policy for the currently running /// Process. This function checks to make sure that kernel32 has the function, /// before calling it. For Windows Systems that don't have DEP. /// /// the specified dep to set /// the return value of the SetProcessDEPPolicy, or false if it doesn't exist public static bool SetProcessDEPPolicy(Definitions.DEP dep) { IntPtr hKernel32 = Kernel32.LoadLibrary("Kernel32.dll"); // Get the DLL if (hKernel32 != IntPtr.Zero) { IntPtr procaddr = IntPtr.Zero; procaddr = Kernel32.GetProcAddress(hKernel32, "SetProcessDEPPolicy"); // Get the Function if (procaddr != null) { // Cast the Delegate SetProcessPolicy = (SetProcessDEPPolicy_Delegate)Marshal.GetDelegateForFunctionPointer(procaddr, typeof(SetProcessDEPPolicy_Delegate)); // Call it * Disabling DEP * return SetProcessPolicy((int)dep); } } return false; } #endregion #region Process / Handle Functionallity public static string GetProcessName(IntPtr hWnd) { int currentPid = 0; User32.GetWindowThreadProcessId(hWnd, ref currentPid); diag.Process process; try { process = diag.Process.GetProcessById(currentPid); } catch (ArgumentException e) { // This is thrown when Process.GetProcessById cannot find the process throw e; } return process.ProcessName; } /// /// Returns the .Net Process Object that owns the passed in hWnd /// /// handle to a Window /// a .Net Process or throws an error public static diag.Process GetProcessFromHandle(IntPtr hWnd) { try { int currentPid = 0; User32.GetWindowThreadProcessId(hWnd, ref currentPid); diag.Process process; process = diag.Process.GetProcessById(currentPid); return process; } catch (ArgumentException e) { // This is thrown when Process.GetProcessById cannot find the process throw e; } } #endregion #region Short / Long FileName N' Path Conversions /// /// Converts a LongFileNameNPath (Modern Windows Path) into a ShortFileNPath (Old Dos 8.3) /// ~File Must exist on the system /// /// Long (Modern Windows Path) FileNameNPath or Path /// Old Dos 8.3 Path public static string GetShortFileNameNPathOrPath(string longFileNameNPathOrPath) { if (String.IsNullOrEmpty(longFileNameNPathOrPath)) return String.Empty; // File MUST exist on the system * Otherwise conversions will fail * if(PathNaming.PathContainsFile(longFileNameNPathOrPath) && !SysIO.File.Exists(longFileNameNPathOrPath)) return String.Empty; // Directory MUST exist on the system * Otherwise conversions will fail * if(!PathNaming.PathContainsFile(longFileNameNPathOrPath) && !SysIO.Directory.Exists(longFileNameNPathOrPath)) return String.Empty; if (String.IsNullOrEmpty(longFileNameNPathOrPath) || !SysIO.Directory.Exists(longFileNameNPathOrPath)) return ""; StringBuilder sb = new StringBuilder(Definitions.MAX_PATH); Kernel32.GetShortPathName(longFileNameNPathOrPath, sb, sb.Capacity); return sb.ToString(); } /// /// Converts a ShortFileNameNPath (Old Dos 8.3) into a long (Modern Windows Path) /// ~File Must exist on the system /// /// Old Dos 8.3 FileNameNPath or Path /// new Modern Windows Path public static string GetLongFileNameNPathOrPath(string shortFileNameNPathOrPath) { if (String.IsNullOrEmpty(shortFileNameNPathOrPath)) return String.Empty; // File MUST exist on the system * Otherwise conversions will fail * if (PathNaming.PathContainsFile(shortFileNameNPathOrPath) && !SysIO.File.Exists(shortFileNameNPathOrPath)) return String.Empty; // Directory MUST exist on the system * Otherwise conversions will fail * if (!PathNaming.PathContainsFile(shortFileNameNPathOrPath) && !SysIO.Directory.Exists(shortFileNameNPathOrPath)) return String.Empty; StringBuilder sb = new StringBuilder(Definitions.MAX_PATH); Kernel32.GetLongPathName(shortFileNameNPathOrPath, sb, sb.Capacity); return sb.ToString(); } #endregion } }