我认为您正在尝试和我做同样的事情——在当前路径从 Explorer 中打开一个 shell。
我遇到了完全相同的问题。这是一个对我有用的程序。它用于EnumWindows
搜索所有可见窗口,直到找到标题为真实路径的窗口。
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
public class ShellHere
{
// Thanks to pinvoke.net for the WinAPI stuff
[DllImport("user32.dll")]
private static extern int EnumWindows(CallBackPtr callPtr, int lPar);
[DllImport("user32.dll")]
static extern int GetWindowText(int hWnd, StringBuilder text, int count);
[DllImport("user32.dll", EntryPoint="GetWindowLong")]
private static extern IntPtr GetWindowLongPtr32(IntPtr hWnd, GWL nIndex);
[DllImport("user32.dll", EntryPoint="GetWindowLongPtr")]
private static extern IntPtr GetWindowLongPtr64(IntPtr hWnd, GWL nIndex);
public delegate bool CallBackPtr(int hwnd, int lParam);
private static CallBackPtr _callBackPtr;
// This static method is required because Win32 does not support
// GetWindowLongPtr directly
public static IntPtr GetWindowLongPtr(IntPtr hWnd, GWL nIndex)
{
if (IntPtr.Size == 8)
return GetWindowLongPtr64(hWnd, nIndex);
else
return GetWindowLongPtr32(hWnd, nIndex);
}
public static bool FindPathInTitle( int hwnd, int lparams )
{
const int nChars = 256;
StringBuilder buffer = new StringBuilder( nChars );
IntPtr result = GetWindowLongPtr( new IntPtr(hwnd), GWL.GWL_STYLE );
// ignore invisible windows
if ( (result.ToInt64() & WS_VISIBLE) != 0 )
{
if ( GetWindowText( hwnd, buffer, nChars ) > 0 )
{
string title = buffer.ToString();
// ignore the taskbar
if ( title.ToLower() != "start" && Directory.Exists( title ) )
{
_folder = title;
return false;
}
}
}
return true;
}
private static string _folder;
public static void Main()
{
_callBackPtr = new CallBackPtr( FindPathInTitle );
EnumWindows( _callBackPtr, 0 );
Process shell = new Process();
shell.StartInfo.FileName = "cmd.exe";
if ( !string.IsNullOrEmpty( _folder ) )
shell.StartInfo.WorkingDirectory = _folder;
shell.Start();
}
public enum GWL
{
GWL_WNDPROC = (-4),
GWL_HINSTANCE = (-6),
GWL_HWNDPARENT = (-8),
GWL_STYLE = (-16),
GWL_EXSTYLE = (-20),
GWL_USERDATA = (-21),
GWL_ID = (-12)
}
// Window Styles
const UInt32 WS_VISIBLE = 0x10000000;
}
到目前为止它对我有用(Win7-64)。请注意,您不必直接在“资源管理器”窗口上即可工作 - 它会使用 Tab 键顺序中的下一个窗口。