Fork me on GitHub

设置窗口不激活(点击时不获取焦点)

直接上代码

 

public static class WindowExtends
{
public static void SetNoActive(this Window window)
{
if (window == null)
{
throw new ArgumentNullException(nameof(window));
}
var hWnd = new WindowInteropHelper(window).Handle;
var style = GetWindowLong(hWnd, GWL_EXSTYLE);
//设置WS_EX_NOACTIVATE属性,不激活焦点属性,这样选中时就不会因为输入焦点切换干扰电脑
if ((style & WS_EX_NOACTIVATE) != WS_EX_NOACTIVATE)//如果不存在则加上
//WS_EX_NOACTIVATE是不激活焦点属性,这样选中时就不会干扰电脑
SetWindowLong(hWnd, GWL_EXSTYLE, style | WS_EX_NOACTIVATE);

}

public static void CancelNoActive(this Window window)
{
if (window == null)
{
throw new ArgumentNullException(nameof(window));
}
var hWnd = new WindowInteropHelper(window).Handle;
var style = GetWindowLong(hWnd, GWL_EXSTYLE);
//存在WS_EX_NOACTIVATE属性 则去掉
if ((style & WS_EX_NOACTIVATE) == WS_EX_NOACTIVATE)
SetWindowLong(hWnd, GWL_EXSTYLE, style & ~WS_EX_NOACTIVATE);

}


private const int GWL_EXSTYLE = -20;//得到扩展的窗口风格
private const int WS_EX_NOACTIVATE = 0x08000000;//使用此样式创建的顶级窗口在用户单击时不会成为前台窗口

private static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong)
{
bool is32BitSystem = IntPtr.Size == 4;
return is32BitSystem ? SetWindowLongPtr32(hWnd, nIndex, dwNewLong) : SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
}
/// <summary>
/// 设置32位系统中窗体的样式
/// </summary>
/// <param name="hWnd"></param>
/// <param name="nIndex"></param>d
/// <param name="dwNewLong"></param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "SetWindowLong")]
private static extern IntPtr SetWindowLongPtr32(IntPtr hWnd, int nIndex, int dwNewLong);

/// <summary>
/// 设置64位系统中窗体的样式
/// </summary>
/// <param name="hWnd"></param>
/// <param name="nIndex"></param>
/// <param name="dwNewLong"></param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "SetWindowLongPtr")]
private static extern IntPtr SetWindowLongPtr64(IntPtr hWnd, int nIndex, int dwNewLong);
/// <summary>
/// 获取窗体句柄
/// </summary>
/// <param name="hwnd"></param>
/// <param name="nIndex"></param>
/// <returns></returns>
[DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hwnd, int nIndex);
}

 

posted @ 2022-09-23 17:14  黄高林  阅读(444)  评论(0编辑  收藏  举报