要实现在WPF窗口位于任务栏之上但不获取焦点的效果,可以使用以下代码示例:
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace WpfApp
{
public partial class MainWindow : Window
{
private const int SWP_NOACTIVATE = 0x0010;
private const int GWL_EXSTYLE = -20;
private const int WS_EX_TOOLWINDOW = 0x00000080;
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
WindowInteropHelper helper = new WindowInteropHelper(this);
IntPtr hWnd = helper.Handle;
int exStyle = GetWindowLong(hWnd, GWL_EXSTYLE);
exStyle |= WS_EX_TOOLWINDOW;
SetWindowLong(hWnd, GWL_EXSTYLE, exStyle);
SetWindowPos(hWnd, new IntPtr(-1), 0, 0, 0, 0, SWP_NOACTIVATE | 0x0201);
}
}
}
在这个示例中,我们使用了 SetWindowLong
和 GetWindowLong
函数来修改窗口的扩展样式,使其具有 WS_EX_TOOLWINDOW
样式,即工具窗口样式。然后,我们使用 SetWindowPos
函数将窗口置于任务栏之上,并禁止它获取焦点。
请注意,在 MainWindow_Loaded
事件处理程序中调用这些函数,以确保窗口加载后应用这些样式和位置更改。
这样,当窗口显示时,它将位于任务栏之上,但不会获取焦点。