Files
Yaulw/Win32/Functions.cs
2016-02-15 12:32:26 -05:00

389 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using SysIO = System.IO;
using Diag = System.Diagnostics;
using Yaulw.Tools;
namespace Yaulw.Win32
{
/// <remarks>
/// Common Win32 .Net Wrapper Functions around Win32 for easier consumption by C#
/// </remarks>
public static class Functions
{
#region Byte / Word
/// <summary>
/// Returns the Low word of the specified int
/// </summary>
/// <param name="n">int to retrieve low word from</param>
/// <returns>low word of the int</returns>
public static int LOWORD(int n) { return (n & 0xffff); }
/// <summary>
/// Returns the Low byte of the specified int
/// </summary>
/// <param name="n">int to retrieve low byte from</param>
/// <returns>low byte of the int</returns>
public static int LOBYTE(int n) { return (n & 0xff); }
/// <summary>
/// Returns the High word of the specified int
/// </summary>
/// <param name="n">int to retrieve high word from</param>
/// <returns>high word of the int</returns>
public static int HIWORD(int n) { return ((n >> 16) & 0xffff); }
/// <summary>
/// Returns the High byte of the specified int
/// </summary>
/// <param name="n">int to retrieve high byte from</param>
/// <returns>high byte of the int</returns>
public static int HIBYTE(int n) { return ((n >> 8) & 0xff); }
#endregion
#region RGB
/// <summary>
/// Win32 RGB
/// </summary>
/// <param name="r">red value as int</param>
/// <param name="g">green value as int</param>
/// <param name="b">blue value as int</param>
/// <returns>returns a Win32 RGB Value as int</returns>
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);
}
/// <summary>
/// Retrieve the Red Value from Win32 RGB Value
/// </summary>
/// <param name="rgbDWORD"></param>
/// <returns>returns Red value</returns>
public static int GetRValue(int rgbDWORD)
{
return LOBYTE(rgbDWORD);
}
/// <summary>
/// Retrieve the Green Value from Win32 RGB Value
/// </summary>
/// <param name="rgbDWORD"></param>
/// <returns>returns Green value</returns>
public static int GetGValue(int rgbDWORD)
{
return (LOBYTE(rgbDWORD >> 8));
}
/// <summary>
/// Retrieve the Blue Value from Win32 RGB Value
/// </summary>
/// <param name="rgbDWORD"></param>
/// <returns>returns Blue value</returns>
public static int GetBValue(int rgbDWORD)
{
return (LOBYTE(rgbDWORD >> 16));
}
#endregion
#region Keyboard Functionallity
/// <summary>
/// Use this Function to determine whether the user is holding down a specified key
/// </summary>
/// <param name="vKey">VK such as Ctrl/Alt/Shift</param>
/// <returns>true if pressed down, false otherwise</returns>
public static bool IsKeyPressed(Definitions.VK vKey)
{
short retVal = User32.GetKeyState(vKey);
return (retVal < 0);
}
#endregion
#region ClientRect Functionallity
/// <summary>
/// Get a windows client rectangle
/// </summary>
/// <param name="hWnd">A Window Handle</param>
/// <returns>A Rectangle</returns>
public static Rectangle GetClientRect(IntPtr hWnd)
{
Structures.RECT rect = new Structures.RECT();
User32.GetClientRect(hWnd, out rect);
return Convert.RECTToRectangle(rect);
}
/// <summary>
/// Get a windows rectangle
/// </summary>
/// <param name="hWnd">The Window handle</param>
/// <returns>A Rectangle</returns>
public static Rectangle GetWindowRect(IntPtr hWnd)
{
Structures.RECT rect = new Structures.RECT();
User32.GetWindowRect(hWnd, out rect);
return Convert.RECTToRectangle(rect);
}
/// <summary>
/// Returns the Client Size, taking into account the Chrome width
/// </summary>
/// <param name="hWnd">A Window Handle</param>
/// <returns>A Rectangle</returns>
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
/// <summary>
/// Use this to get the name of a Window Class
/// </summary>
/// <param name="hWnd">A Window Handle</param>
/// <returns>The name of the Window Class</returns>
public static string GetWindowClassName(IntPtr hWnd)
{
StringBuilder ClassName = new StringBuilder(100);
int nRet = User32.GetClassName(hWnd, ClassName, ClassName.Capacity);
return ClassName.ToString();
}
/// <summary>
/// Use this to get the text of a Window
/// </summary>
/// <param name="hWnd">A Window Handle</param>
/// <returns>The window Text</returns>
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();
}
/// <summary>
/// Get the Window Text of a Dialog Item
/// </summary>
/// <param name="hDlg">handle to Dialog</param>
/// <param name="nIDDlgItem">uint Dialog Item</param>
/// <returns>Window Text from the Dialog Item</returns>
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);
}
/// <summary>
/// Use this to retrieve the Process Object for a specific Window Handle
/// </summary>
/// <param name="hWnd">A Window Handle</param>
/// <returns>A valid Process object or Null if error occured</returns>
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;
}
/// <summary>
/// Find the first top level window for the specified process
/// </summary>
/// <param name="pid">Process ID</param>
/// <returns>the hWnd for the first Window of the specifed or IntPtr.Zero if none found</returns>
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;
}
/// <summary>
///
/// </summary>
/// <param name="pid"></param>
/// <returns></returns>
public static IntPtr GetTopLevelChildWindowForProcess(int pid)
{
// To Do
return IntPtr.Zero;
}
#endregion
#region Desktop Window Functionallity
/// <summary>
/// Get's the Desktop Window as a Win32Window Object
/// </summary>
/// <returns>a Win32Window Object</returns>
public static IWin32Window GetDestopWindow()
{
return Convert.ConverthWndToIWin32Window(User32.GetDesktopWindow());
}
/// <summary>
/// Refreshes orphaned Icons in the Taskbar
/// <seealso cref="http://stackoverflow.com/questions/74723/can-you-send-a-signal-to-windows-explorer-to-make-it-refresh-the-systray-icons"/>
/// <seealso cref="http://malwareanalysis.com/CommunityServer/blogs/geffner/archive/2008/02/15/985.aspx"/>
/// </summary>
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;
/// <summary>
/// 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.
/// </summary>
/// <param name="dep">the specified dep to set</param>
/// <returns>the return value of the SetProcessDEPPolicy, or false if it doesn't exist</returns>
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 Short / Long FileName N' Path Conversions
/// <summary>
/// Converts a LongFileNameNPath (Modern Windows Path) into a ShortFileNPath (Old Dos 8.3)
/// ~File Must exist on the system
/// </summary>
/// <param name="longFileNameNPath">Long (Modern Windows Path) FileNameNPath or Path</param>
/// <returns>Old Dos 8.3 Path</returns>
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();
}
/// <summary>
/// Converts a ShortFileNameNPath (Old Dos 8.3) into a long (Modern Windows Path)
/// ~File Must exist on the system
/// </summary>
/// <param name="shortFileNameNPathOrPath">Old Dos 8.3 FileNameNPath or Path</param>
/// <returns>new Modern Windows Path</returns>
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
}
}