在单个可用实例中打开文件夹或选定文件

Opening Folder or to Selected File in Single, Usable Instance

我正在尝试在我的应用程序中创建一个 'Show' 按钮。我希望这可以打开 Windows Explorer 进入所选文件夹,或者打开文件夹并突出显示所选文件。

我知道 Process.Start("explorer.exe", fileName) 会执行此操作,但它会在无法导航的资源管理器版本中打开。例如按 'Up Directory' 打开一个新的 window.

我在下面得到的代码可以完成我想要的一切,除了当路径是一个文件时,它会在每次单击按钮时打开一个新的 window 实例。而当路径是一个文件夹时,它会打开一个已经存在的 window 如果该路径存在。

我希望我可以拥有相同的文件选择功能。但是我不知道该怎么做。

感谢任何帮助!

static void OpenInWin(string path) {
    path = path.Replace("/", "\");

    ProcessStartInfo pi = new ProcessStartInfo("explorer.exe") {
        WindowStyle = ProcessWindowStyle.Normal,
        UseShellExecute = true
    };

    if (Directory.Exists(path)) { // We are opening a directory
        pi.FileName = path;
        pi.Verb = "open";
    } else {
        pi.Arguments = "/select, \"" + new FileInfo(path).FullName + "\"";
    }

    try {
        Process.Start(pi);
    } catch(Exception e) {
        UnityEngine.Debug.Log(e);
    }
}

下面的方法将从传递的路径中获取目录,然后打开该目录。打开该目录后,它将关注文件名(如果存在)。

记得为 SendKeys 添加 using System.Windows.Forms;

static void OpenInWin(string path)
{
    path = path.Replace("/", "\");
    FileInfo fileInfo = new FileInfo(path);

    //check if directory exists so that 'fileInfo.Directory' doesn't throw directory not found

    ProcessStartInfo pi = new ProcessStartInfo("explorer.exe")
    {
        WindowStyle = ProcessWindowStyle.Normal,
        UseShellExecute = true,
        FileName = fileInfo.Directory.FullName,
        Verb = "open"
    };

    try
    {
        Process.Start(pi);
        Thread.Sleep(500); // can set any delay here
        SendKeys.SendWait(fileInfo.Name);
    }
    catch (Exception e)
    {
        throw new Exception(e.Message, e);
    }
}


注意:可能有更好的方法将密钥发送到进程。您可以尝试以下方法:

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

public static void SendKey()
{
    Process notepad = new Process();
    notepad.StartInfo.FileName = @"C:\Windows\Notepad.exe";
    notepad.Start();

    notepad.WaitForInputIdle();

    IntPtr p = notepad.MainWindowHandle;
    ShowWindow(p, 1);
    SendKeys.SendWait("Text sent to notepad");
}

编辑:

要在没有 Windows Forms Context 的情况下生成关键事件, 我们可以使用下面的方法,

[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

示例代码如下:

const int VK_UP = 0x26; //up key
    const int VK_DOWN = 0x28;  //down key
    const int VK_LEFT = 0x25;
    const int VK_RIGHT = 0x27;
    const uint KEYEVENTF_KEYUP = 0x0002;
    const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
   static int press()
   {

//Press the key
        keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
        return 0; 

   }

已定义虚拟键列表 here

要获得完整的图片,请使用下面的link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html