views:

172

answers:

2

In a WPF application, when a user clicks on a button I want to open the Windows explorer to a certain directory, how do I do that?

I would expect something like this:

Windows.OpenExplorer("c:\test");
+1  A: 

What about Application.Run("explorer.exe")?

oops. That was not WPF, but WinForms, I guess. Use something like the following, which will launch explorer.exe. You can use the fourth parameter to ShellExecute to give it a starting directory.

public partial class Window1 : Window
{
    public Window1()
    {
        ShellExecute(IntPtr.Zero, "open", "explorer.exe", "", "", ShowCommands.SW_NORMAL);
        InitializeComponent();
    }

    public enum ShowCommands : int
    {
        SW_HIDE = 0,
        SW_SHOWNORMAL = 1,
        SW_NORMAL = 1,
        SW_SHOWMINIMIZED = 2,
        SW_SHOWMAXIMIZED = 3,
        SW_MAXIMIZE = 3,
        SW_SHOWNOACTIVATE = 4,
        SW_SHOW = 5,
        SW_MINIMIZE = 6,
        SW_SHOWMINNOACTIVE = 7,
        SW_SHOWNA = 8,
        SW_RESTORE = 9,
        SW_SHOWDEFAULT = 10,
        SW_FORCEMINIMIZE = 11,
        SW_MAX = 11
    }

    [DllImport("shell32.dll")]
    static extern IntPtr ShellExecute(
        IntPtr hwnd,
        string lpOperation,
        string lpFile,
        string lpParameters,
        string lpDirectory,
        ShowCommands nShowCmd);
}

The declarations come from the pinvoke.net website.

Abel
yes, i was getting errors chasing that, didn't know about <strike>strike</strike> btw cool
Edward Tanguay
which, unfortunately, only works in answers / questions, but not in comments ;-). I just updated.
Abel
+1 I'll use this code to launch other apps, but the Process.Start() was exactly what I needed.
Edward Tanguay
that's what happens when you try to answer q. a 3AM: you miss the obvious ;-). Anyway, I remember I often use ShellExecute when Process.Start does not what I want (there are few scenarios that it can't handle).
Abel
+4  A: 

Why not Process.Start(@"c:\test");?

Jamie Penney
Note: You can use this to run other applications as well. `Process.Start("calc.exe");` will run Calculator. You can pass it the full path to an executable and it will run it.
Jamie Penney
LOL, yes, why not. Funny, had Application.Run in my head, couldn't get to the ubiquitous Process.Start and thought WPF was playing games with me.
Abel