Search code examples
c#wpfwinforms

Calling SHAppBarMessage to set the taskbar works from ApplicationContext but not from WPF Application


I have the following code to set the taskbar to auto hide using Interop.

public void SetTaskbarState(AppBarStates option)
{
    APPBARDATA msgData = new APPBARDATA();
    msgData.cbSize = (UInt32)Marshal.SizeOf(msgData);
    msgData.hWnd = Handle;
    msgData.lParam = (Int32)(option);
    SHAppBarMessage((UInt32)AppBarMessages.SetState, ref msgData);
}

public static IntPtr Handle
{
    get
    {
        return FindWindow("Shell_TrayWnd", "");
    }
}

I have an old WinForms application where I have a class that inherits from ApplicationContext. I am calling SetTaskbarState from the constructor of that class

public class MyContext : ApplicationContext
{
    public MyContext() 
    {
        SetTaskbarState(AppBarStates.AutoHide);
    }
}

The above works flawlessly and hides the taskbar.

In my WPF application that I am migrating to, I have a class called App that inherits from System.Windows.Application.

I have tried calling the same in the constructor, in the OnStartup method, and OnLoadCompleted method. No matter what it does not hide the taskbar like it does in the WinForms application.

protected override void OnStartup(StartupEventArgs e)
{
    // verified this is true but also have removed the if
    if (Settings.Instance.UI.HideTaskbar == true)
    {
        _taskbar.SetTaskbarState(AppBarStates.AutoHide);
    }

    base.OnStartup(e);

    // i have also tried calling it here
}

How can I hide the taskbar properly from within a WPF app?

EDIT: I verified that the call to Handle in both cases returns the same value.

windws version


Solution

  • In Windows 11 it is now System_TrayWnd

    public static IntPtr Handle
    {
        get
        {
            return FindWindow("Shell_TrayWnd", "");
        }
    }
    

    Needs to be

    public static IntPtr Handle
    {
        get
        {
            return FindWindow("System_TrayWnd", "");
        }
    }