[WPF]使用WinForm控件后无边框窗口实现
有时需要在WPF程序中需要嵌入WinForm的控件,这时如果用WindowStyle="None"
、AllowsTransparency="True"
和Background="Transparent"
设置无边框窗口就会发现不显示任何东西。这时就需要调用系统API来实现无边框窗口。
设置窗口无边框
设置无边框需要用SetWindowLong
,代码如下:
private const int GWL_STYLE = -16;
private const int WS_CAPTION = 0X00C0000;
[DllImport("user32", EntryPoint = "SetWindowLong")]
private static extern int SetWindowLong(IntPtr hwnd, int nIndex, int dwNewLong);
/// <summary>
/// 设置窗口无边框
/// </summary>
/// <param name="window">要设置的窗口</param>
/// <param name="isNoBorder">是否为无边框窗口</param>
public static void SetWindowNoBorder(this Window window, bool isNoBorder)
{
if (window == null) return;
// 获取窗体句柄
var hwnd = new WindowInteropHelper(window).Handle;
// 获得窗体的 样式
var oldstyle = GetWindowLong(hwnd, GWL_STYLE);
if (isNoBorder)
SetWindowLong(hwnd, GWL_STYLE, oldstyle & ~WS_CAPTION);
else
SetWindowLong(hwnd, GWL_STYLE, oldstyle | WS_CAPTION);
}
设置窗口背景透明
设置背景透明需要用SetLayeredWindowAttributes
,代码如下: ···