Open the “open”-dialogbox from cmd

2019-07-20 15:01发布

I want to know if I can open the "open"-dialogbox from the cmd, so I can use that to choose the right file to open. (I already know how to open the file directly from the cmd, but thats not what I interested in)

At the moment I'm doing a project where i use a program (e.g. program.exe). This program needs a modelfile (e.g. modelfile.mod). I execute the program in the CMD by writing: program.exe modelfile.mod, and it work. I have many modelfiles with different names, but the program file always has the same name. Instead of writing in the CMD every time I need to execute the program I would like to create a batch where I can choose the modfile I like to execute whereafter it executes the program with the chosen modfile as input.

Therefore I need to know how to open the "open"-dialogbox from the cmd, and also how to get the name of the chosen file for use in execution of the program.

标签: file cmd
1条回答
老娘就宠你
2楼-- · 2019-07-20 15:28

If you've got PowerShell installed, you can do something like this:

@echo off
setlocal
set ps_cmd=powershell "Add-Type -AssemblyName System.windows.forms|Out-Null;$f=New-Object System.Windows.Forms.OpenFileDialog;$f.Filter='Model Files (*.mod)|*.mod|All files (*.*)|*.*';$f.showHelp=$true;$f.ShowDialog()|Out-Null;$f.FileName"

for /f "delims=" %%I in ('%ps_cmd%') do set "filename=%%I"

if defined filename (
    echo You chose %filename%
) else (
    echo You didn't choose squat!
)

goto :EOF

Or if you want to break down the powershell cmdlets for easier maintenance:

@echo off
setlocal
set "ps=Add-Type -AssemblyName System.windows.forms | Out-Null;"
set "ps=%ps% $f=New-Object System.Windows.Forms.OpenFileDialog;"
set "ps=%ps% $f.Filter='Model Files (*.mod)|*.mod|All files (*.*)|*.*';"
set "ps=%ps% $f.showHelp=$true;"
set "ps=%ps% $f.ShowDialog() | Out-Null;"
set "ps=%ps% $f.FileName"

for /f "delims=" %%I in ('powershell "%ps%"') do set "filename=%%I"

if defined filename (
    echo You chose %filename%
) else (
    echo You didn't choose squat!
)

goto :EOF

(PowerShell command mercilessly leeched from the Just Tinkering Blog.) See the OpenFileDialog Class documentation for other properties you can set, such as Title and InitialDirectory.

查看更多
登录 后发表回答