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

时间:2016-04-06 03:41:15

标签: c# process windows-explorer file-browser

我正在尝试在我的应用程序中创建一个“显示”按钮。我想要将Windows资源管理器打开到所选文件夹中,或者打开文件夹并突出显示所选文件。

我知道Process.Start(“explorer.exe”,fileName)执行此操作,但它在无法导航的资源管理器版本中打开。例如,按“向上目录”会打开一个新窗口。

我下面的代码执行了我想要的所有操作,除了当路径是文件时,每次单击按钮时它都会打开一个新的窗口实例。而当路径是文件夹时,如果该路径存在,则会打开一个已存在的窗口。

我希望我能为文件选择提供相同的功能。但我无法弄明白该怎么做。

感谢任何和所有帮助!

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);
    }
}

1 个答案:

答案 0 :(得分:-1)

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

请务必在using System.Windows.Forms;中加入SendKeys

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窗体上下文的情况下生成关键事件, 我们可以使用以下方法,

[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

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