Is there a way to close a particular instance of explorer with C#?

后端 未结 4 2059
故里飘歌
故里飘歌 2020-12-01 19:17

I\'m looking for a way to close a Windows explorer window that\'s open to a certain folder. Say c:\\users\\bob\\folder. I can close all explorers with the code below, but th

4条回答
  •  天命终不由人
    2020-12-01 19:30

    This works. It's a follow up on Jeff Roe's post.

    // Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.
    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    public static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
    
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, StringBuilder lParam);
    
    // caption is the window title.
    public void CloseWindowsExplorer(string caption)
    {
        IntPtr i = User32.FindWindowByCaption(IntPtr.Zero, caption);
        if (i.Equals(IntPtr.Zero) == false)
        {
            // WM_CLOSE is 0x0010
            IntPtr result = User32.SendMessage(i, 0x0010, IntPtr.Zero, null);
        }
    }
    

提交回复
热议问题