Skip to content

Instantly share code, notes, and snippets.

@xv
Created March 4, 2020 09:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save xv/fe38d7ad8d8f545be76a8575481085e3 to your computer and use it in GitHub Desktop.
Flashes a screen-inverted rectangle around a window like in Microsoft Spy++.
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
[DllImport("user32.dll")]
static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
static extern int SaveDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
static extern int SetROP2(IntPtr hdc, int fnDrawMode);
[DllImport("user32.dll")]
static extern int GetSystemMetrics(int smIndex);
[DllImport("gdi32.dll")]
static extern IntPtr CreatePen(int fnPenStyle, int nWidth, int crColor);
[DllImport("gdi32.dll")]
static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport("gdi32.dll")]
static extern IntPtr GetStockObject(int i);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool Rectangle(IntPtr hdc, int nLeftRect, int nTopRect,
int nRightRect, int nBottomRect);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RestoreDC(IntPtr hdc, int nSavedDC);
[DllImport("user32.dll")]
static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
[StructLayout(LayoutKind.Explicit)]
struct RECT
{
[FieldOffset(0)]
int left;
[FieldOffset(4)]
int top;
[FieldOffset(8)]
int right;
[FieldOffset(12)]
int bottom;
int Width
{
get { return right - left; }
set
{
left += value;
right -= value;
}
}
int Height
{
get { return bottom - top; }
set
{
top += value;
bottom -= value;
}
}
}
const int R2_NOT = 0x6,
SM_CXBORDER = 0x5,
PS_INSIDEFRAME = 0x6,
NULL_BRUSH = 0x5;
static void InvertWindowBorder(IntPtr hwnd)
{
if (hwnd == IntPtr.Zero)
return;
RECT rect;
GetWindowRect(hwnd, out rect);
if (rect.Width == 0 && rect.Height == 0)
return;
var hDc = GetWindowDC(hwnd);
if (hDc == IntPtr.Zero)
return;
var savedDc = SaveDC(hDc);
SetROP2(hDc, R2_NOT);
var penWidth = GetSystemMetrics(SM_CXBORDER) * 3;
var hPen = CreatePen(PS_INSIDEFRAME, penWidth, 0);
SelectObject(hDc, hPen);
var hBrush = GetStockObject(NULL_BRUSH);
SelectObject(hDc, hBrush);
Rectangle(hDc, 0, 0, rect.Width, rect.Height);
DeleteObject(hPen);
DeleteObject(hBrush);
RestoreDC(hDc, savedDc);
ReleaseDC(hwnd, hDc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment