Win 7中的“pin to desktop”,兼容XP

时间:2010-07-28 08:00:47

标签: c# windows-7 desktop

我如何使用FindWindow + SetParent方法或者在XP中可以使用的任何其他方法在Win 7中实现“引脚到桌面”效果(即免受“显示桌面”命令)的影响? 我知道我可以创建一个小工具,但是我希望能够向后兼容XP,我可以将这段代码做得很好:

IntPtr hWnd = FindWindow(null, "Untitled - Notepad");
IntPtr hDesktop = FindWindow("ProgMan", "Program Manager");
SetParent(hWnd, hDesktop);

3 个答案:

答案 0 :(得分:2)

在我的WPF应用程序中,我能够使用计时器解决它,它在XP和Win 7中都有效。

public MainWindow()
{
    InitializeComponent();

    // have some timer to fire in every 1 second
    DispatcherTimer detectShowDesktopTimer = new DispatcherTimer();
    detectShowDesktopTimer.Tick += new EventHandler(detectShowDesktopTimer_Tick);
    detectShowDesktopTimer.Interval = new TimeSpan(0, 0, 1);
    detectShowDesktopTimer.Start();
}

#region support immunizing against "Show Desktop"
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

private string GetWindowText(IntPtr handle)
{
    int chars = 256;
    StringBuilder buff = new StringBuilder(chars);
    if (GetWindowText(handle, buff, chars) > 0)
        return buff.ToString();
    else
        return string.Empty;
}
#endregion

private void detectShowDesktopTimer_Tick(object sender, EventArgs e)
{
    IntPtr fore = GetForegroundWindow();
    if (string.IsNullOrWhiteSpace(GetWindowText(fore)))
        ShowDesktopDetected();
}

private void ShowDesktopDetected()
{
    WindowInteropHelper wndHelper = new WindowInteropHelper(this);
    SetForegroundWindow(wndHelper.Handle);
}

答案 1 :(得分:2)

在处理粘贴到桌面上的日历时,我遇到了同样的问题。 这是我的解决方案:

/************ win32 interop stuff ****************/


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

[DllImport( "user32.dll", SetLastError = true )]
static extern IntPtr FindWindow( string lpWindowClass, string lpWindowName );

[DllImport( "user32.dll", SetLastError = true )]
static extern IntPtr FindWindowEx( IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle );


const int GWL_HWNDPARENT = -8;


/************* in Form_Load or equivalent ***************/


IntPtr hprog = FindWindowEx(
    FindWindowEx(
        FindWindow( "Progman", "Program Manager" ),
        IntPtr.Zero, "SHELLDLL_DefView", ""
    ),
    IntPtr.Zero, "SysListView32", "FolderView"
);

SetWindowLong( this.Handle, GWL_HWNDPARENT, hprog );

棘手的部分是设置表单的所有者(SetWindowLong + GWL_HWNDPARENT)而不是表单的父(SetParent)。这修复了未在航空桌面上呈现的表单。

答案 2 :(得分:0)

这个问题的答案应该有所帮助:

如果没有,您可以在XP中将其实现为活动桌面应用程序。或者,如果它是一个简单的仅查看应用程序,您实际上可以在桌面壁纸上绘制。