C# Winform 窗體美化(五、滑鼠穿透)
阿新 • • 發佈:2019-01-28
五、滑鼠穿透
以前在玩射擊遊戲的時候,狙擊槍的設定一般是開鏡才有準星,所以想是不是可以自己造一個默認準星出來,思路是現在視窗上畫一個準星,然後把窗體其他區域都透明,然後設定滑鼠穿透;
結果是:
- UpdateLayeredWindow 的不規則視窗中,新增滑鼠穿透功能導致不規則視窗失效。
- GraphicsPathForm 的不規則視窗中,可以愉快地使用滑鼠穿透功能。
注意:
全屏的遊戲,視窗是不能最前的,可以先把遊戲設定成視窗模式(尷尬),一般遊戲切換全屏的按鍵是“alt+enter”。
程式碼如下:
private const uint WS_EX_LAYERED = 0x80000 ;
private const int WS_EX_TRANSPARENT = 0x20;
private const int GWL_STYLE = (-16);
private const int GWL_EXSTYLE = (-20);
private const int LWA_ALPHA = 0;
[DllImport("user32", EntryPoint = "SetWindowLong")]
private static extern uint SetWindowLong(
IntPtr hwnd,
int nIndex,
uint dwNewLong
);
[DllImport("user32" , EntryPoint = "GetWindowLong")]
private static extern uint GetWindowLong(
IntPtr hwnd,
int nIndex
);
[DllImport("user32", EntryPoint = "SetLayeredWindowAttributes")]
private static extern int SetLayeredWindowAttributes(
IntPtr hwnd,
int crKey,
int bAlpha,
int dwFlags
);
/// <summary>
/// 設定窗體具有滑鼠穿透效果
/// </summary>
public void SetPenetrate()
{
this.TopMost = true;
SetWindowLong(this.Handle, GWL_EXSTYLE, WS_EX_TRANSPARENT | WS_EX_LAYERED);
SetLayeredWindowAttributes(this.Handle, 0, 100, LWA_ALPHA);
}