设置Windows任务栏为前台窗口/进程



我想把Windows任务栏设置为前台窗口,就像当用户点击它时一样。你可以看到它被聚焦了,因为以前活动的窗口不再在任务栏中标记了。

我尝试SetForegroundWindow通过获取hwnd与FindWindow,但这没有做什么:

SetForegroundWindow(FindWindow("System_TrayWnd", null));

特别是我想防止任务栏自动隐藏时,自动隐藏选项是启用的。我不想暂时禁用自动隐藏选项,因为这会导致打开的窗口在位置上移动。如果用户点击任务栏,只要它处于聚焦状态,它就会停止自动隐藏。

如何设置Windows任务栏的焦点?

你需要使用SetWindowPos而不是SetForegroundWindow,并给它一个标志来显示窗口。根据文档,该标志是0x0040。

然后,如果你想让它真正有焦点,那么你可以调用SetForegroundWindow

[DllImport("user32.dll", SetLastError = true)]
private static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);

下面是一个简单的"show"示例

MainWindow.xaml

<Window x:Class="_65994896.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Show Taskbar" Click="Button_Click"/>
</Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Runtime.InteropServices;
using System.Windows;
namespace _65994896
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr FindWindow( string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
private static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
[Flags]
private enum SetWindowPosFlags : uint
{
SWP_HIDEWINDOW = 0x0080,
SWP_SHOWWINDOW = 0x0040
}
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var window = FindWindow("Shell_traywnd", "");
SetWindowPos(window, IntPtr.Zero, 0, 0, 0, 0, (uint)SetWindowPosFlags.SWP_SHOWWINDOW);
}
}
}

最新更新