对 Alt-Tab 程序切换器隐藏窗口的最佳方法?

我一直是个。NET 开发人员已经好几年了,这仍然是我不知道如何正确地做的事情之一。通过 Windows 窗体和 WPF 中的属性很容易在任务栏中隐藏窗口,但据我所知,这并不能保证(甚至不一定影响)它在 Alt + ↹Tab对话框中被隐藏。我已经看到 隐形的窗口显示在 Alt + ↹Tab,我只是想知道什么是最好的方式来保证一个窗口将 永远不会出现(可见或不)在 Alt + ↹Tab对话框。

更新: 请看下面我发布的解决方案。我不被允许把自己的答案标记为解决方案,但到目前为止,这是唯一有效的方法。

更新2: 弗朗西斯 · 佩诺夫现在有一个合适的解决方案,看起来很不错,但是我自己还没有试过。包括一些 Win32,但避免了创建蹩脚的离屏窗口。

67516 次浏览

Personally as far as I know this is not possible without hooking into windows in some fashion, I'm not even sure how that would be done or if it is possible.

Depending on your needs, developing your application context as a NotifyIcon (system tray) application will allow it to be running without showing in ALT + TAB. HOWEVER, if you open a form, that form will still follow the standard functionality.

I can dig up my blog article about creating an application that is ONLY a NotifyIcon by default if you want.

In XAML set ShowInTaskbar="False":

<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ShowInTaskbar="False"
Title="Window1" Height="300" Width="300">
<Grid>


</Grid>
</Window>

Edit: That still shows it in Alt+Tab I guess, just not in the taskbar.

I've found a solution, but it's not pretty. So far this is the only thing I've tried that actually works:

Window w = new Window(); // Create helper window
w.Top = -100; // Location of new window is outside of visible part of screen
w.Left = -100;
w.Width = 1; // size of window is enough small to avoid its appearance at the beginning
w.Height = 1;
w.WindowStyle = WindowStyle.ToolWindow; // Set window style as ToolWindow to avoid its icon in AltTab
w.Show(); // We need to show window before set is as owner to our main window
this.Owner = w; // Okey, this will result to disappear icon for main window.
w.Hide(); // Hide helper window just in case

Found it here.

A more general, reusable solution would be nice. I suppose you could create a single window 'w' and reuse it for all windows in your app that need to be hidden from the Alt+↹Tab.

Update: Ok so what I did was move the above code, minus the this.Owner = w bit (and moving w.Hide() immediately after w.Show(), which works fine) into my application's constructor, creating a public static Window called OwnerWindow. Whenever I want a window to exhibit this behavior, I simply set this.Owner = App.OwnerWindow. Works great, and only involves creating one extra (and invisible) window. You can even set this.Owner = null if you want the window to reappear in the Alt+↹Tab dialog.

Thanks to Ivan Onuchin over on MSDN forums for the solution.

Update 2: You should also set ShowInTaskBar=false on w to prevent it from flashing briefly in the taskbar when shown.

Don't show a form. Use invisibility.

More here: http://code.msdn.microsoft.com/TheNotifyIconExample

Update:

According to @donovan, modern days WPF supports this natively, through setting ShowInTaskbar="False" and Visibility="Hidden" in the XAML. (I haven't tested this yet, but nevertheless decided to bump the comment visibility)

Original answer:

There are two ways of hiding a window from the task switcher in Win32 API:

  1. to add the WS_EX_TOOLWINDOW extended window style - that's the right approach.
  2. to make it a child window of another window.

Unfortunately, WPF does not support as flexible control over the window style as Win32, thus a window with WindowStyle=ToolWindow ends up with the default WS_CAPTION and WS_SYSMENU styles, which causes it to have a caption and a close button. On the other hand, you can remove these two styles by setting WindowStyle=None, however that will not set the WS_EX_TOOLWINDOW extended style and the window will not be hidden from the task switcher.

To have a WPF window with WindowStyle=None that is also hidden from the task switcher, one can either of two ways:

  • go with the sample code above and make the window a child window of a small hidden tool window
  • modify the window style to also include the WS_EX_TOOLWINDOW extended style.

I personally prefer the second approach. Then again, I do some advanced stuff like extending the glass in the client area and enabling WPF drawing in the caption anyway, so a little bit of interop is not a big problem.

Here's the sample code for the Win32 interop solution approach. First, the XAML part:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300"
ShowInTaskbar="False" WindowStyle="None"
Loaded="Window_Loaded" >

Nothing too fancy here, we just declare a window with WindowStyle=None and ShowInTaskbar=False. We also add a handler to the Loaded event where we will modify the extended window style. We can't do that work in the constructor, as there's no window handle at that point yet. The event handler itself is very simple:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
WindowInteropHelper wndHelper = new WindowInteropHelper(this);


int exStyle = (int)GetWindowLong(wndHelper.Handle, (int)GetWindowLongFields.GWL_EXSTYLE);


exStyle |= (int)ExtendedWindowStyles.WS_EX_TOOLWINDOW;
SetWindowLong(wndHelper.Handle, (int)GetWindowLongFields.GWL_EXSTYLE, (IntPtr)exStyle);
}

And the Win32 interop declarations. I've removed all unnecessary styles from the enums, just to keep the sample code here small. Also, unfortunately the SetWindowLongPtr entry point is not found in user32.dll on Windows XP, hence the trick with routing the call through the SetWindowLong instead.

#region Window styles
[Flags]
public enum ExtendedWindowStyles
{
// ...
WS_EX_TOOLWINDOW = 0x00000080,
// ...
}


public enum GetWindowLongFields
{
// ...
GWL_EXSTYLE = (-20),
// ...
}


[DllImport("user32.dll")]
public static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);


public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
{
int error = 0;
IntPtr result = IntPtr.Zero;
// Win32 SetWindowLong doesn't clear error on success
SetLastError(0);


if (IntPtr.Size == 4)
{
// use SetWindowLong
Int32 tempResult = IntSetWindowLong(hWnd, nIndex, IntPtrToInt32(dwNewLong));
error = Marshal.GetLastWin32Error();
result = new IntPtr(tempResult);
}
else
{
// use SetWindowLongPtr
result = IntSetWindowLongPtr(hWnd, nIndex, dwNewLong);
error = Marshal.GetLastWin32Error();
}


if ((result == IntPtr.Zero) && (error != 0))
{
throw new System.ComponentModel.Win32Exception(error);
}


return result;
}


[DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", SetLastError = true)]
private static extern IntPtr IntSetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);


[DllImport("user32.dll", EntryPoint = "SetWindowLong", SetLastError = true)]
private static extern Int32 IntSetWindowLong(IntPtr hWnd, int nIndex, Int32 dwNewLong);


private static int IntPtrToInt32(IntPtr intPtr)
{
return unchecked((int)intPtr.ToInt64());
}


[DllImport("kernel32.dll", EntryPoint = "SetLastError")]
public static extern void SetLastError(int dwErrorCode);
#endregion

Form1 Properties:
FormBorderStyle: Sizable
WindowState: Minimized
ShowInTaskbar: False

private void Form1_Load(object sender, EventArgs e)
{
// Making the window invisible forces it to not show up in the ALT+TAB
this.Visible = false;
}>

Why so complex? Try this:

me.FormBorderStyle = FormBorderStyle.SizableToolWindow
me.ShowInTaskbar = false

Idea taken from here:http://www.csharp411.com/hide-form-from-alttab/

Here's what does the trick, regardless of the style of the window your are trying to hide from Alt+↹Tab.

Place the following into the constructor of your form:

// Keep this program out of the Alt-Tab menu


ShowInTaskbar = false;


Form form1 = new Form ( );


form1.FormBorderStyle = FormBorderStyle.FixedToolWindow;
form1.ShowInTaskbar = false;


Owner = form1;

Essentially, you make your form a child of an invisible window which has the correct style and ShowInTaskbar setting to keep out of the Alt-Tab list. You must also set your own form's ShowInTaskbar property to false. Best of all, it simply doesn't matter what style your main form has, and all tweaking to accomplish the hiding is just a few lines in the constructor code.

see it:(from http://bytes.com/topic/c-sharp/answers/442047-hide-alt-tab-list#post1683880)

[DllImport("user32.dll")]
public static extern int SetWindowLong( IntPtr window, int index, int
value);
[DllImport("user32.dll")]
public static extern int GetWindowLong( IntPtr window, int index);




const int GWL_EXSTYLE = -20;
const int WS_EX_TOOLWINDOW = 0x00000080;
const int WS_EX_APPWINDOW = 0x00040000;


private System.Windows.Forms.NotifyIcon notifyIcon1;




// I use two icons depending of the status of the app
normalIcon = new Icon(this.GetType(),"Normal.ico");
alertIcon = new Icon(this.GetType(),"Alert.ico");
notifyIcon1.Icon = normalIcon;


this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
this.Visible = false;
this.ShowInTaskbar = false;
iconTimer.Start();


//Make it gone frmo the ALT+TAB
int windowStyle = GetWindowLong(Handle, GWL_EXSTYLE);
SetWindowLong(Handle, GWL_EXSTYLE, windowStyle | WS_EX_TOOLWINDOW);

I tried setting the main form's visibility to false whenever it is automatically changed to true:

private void Form1_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible)
{
this.Visible = false;
}
}

It works perfectly :)

Why trying so much codes? Just set the FormBorderStyle propety to FixedToolWindow. Hope it helps.

if you want the form to be borderless, then you need to add the following statements to the form’s constructor:

this.FormBorderStyle = FormBorderStyle.None;
this.ShowInTaskbar = false;

AND you must add the following method to your derived Form class:

protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
// turn on WS_EX_TOOLWINDOW style bit
cp.ExStyle |= 0x80;
return cp;
}
}

more details

Inside your form class, add this:

protected override CreateParams CreateParams
{
get
{
var Params = base.CreateParams;
Params.ExStyle |= WS_EX_TOOLWINDOW;
return Params;
}
}

It's as easy as that; works a charm!

I tried This. It works for me

  private void Particular_txt_KeyPress(object sender, KeyPressEventArgs e)
{
Form1 frm = new Form1();
frm.Owner = this;
frm.Show();
}

Solution for those who want a WPF window to stay visible while hidden from the Alt+Tab switcher:

Hide a WPF window from Alt+Tab