【问题标题】:Set Windows taskbar as foreground window/process将 Windows 任务栏设置为前台窗口/进程
【发布时间】:2021-02-01 14:56:34
【问题描述】:

我想将 Windows 任务栏设置为前台窗口,就像用户单击它时一样。您可以看到它已聚焦,因为先前活动的窗口不再在任务栏中标记。

我尝试通过使用FindWindow 获取 hwnd 来尝试SetForegroundWindow,但这无济于事:

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

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

如何将焦点设置到 Windows 任务栏?

【问题讨论】:

  • 也许模拟鼠标点击可以吗?您想通过激活任务栏来解决什么问题?需要什么?
  • 您是否希望您的应用不获得焦点(例如 here)?
  • 听起来像XY Problem。您最终要解决什么问题
  • 您想在您的应用处于活动状态时显示自动隐藏的任务栏吗?
  • 您是如何将搜索框嵌入到任务栏中的?

标签: c# wpf winapi


【解决方案1】:

您需要使用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);

这是任务栏“显示”的一个简单工作示例:

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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    相关资源
    最近更新 更多