显示来自 Windows 批处理文件的弹出/消息框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/774175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:16:34  来源:igfitidea点击:

Show a popup/message box from a Windows batch file

windowsbatch-filecommand-linemessagebox

提问by billyy

Is there a way to display a message box from a batch file (similar to how xmessagecan be used from bash-scripts in Linux)?

有没有办法从批处理文件中显示消息框(类似于如何xmessage从 Linux 中的 bash 脚本使用)?

采纳答案by boflynn

I would make a very simple VBScript file and call it using CScript to parse the command line parameters.

我会制作一个非常简单的 VBScript 文件并使用 CScript 调用它来解析命令行参数。

Something like the following saved in MessageBox.vbs:

类似以下内容保存在MessageBox.vbs

Set objArgs = WScript.Arguments
messageText = objArgs(0)
MsgBox messageText

Which you would call like:

你会称之为:

cscript MessageBox.vbs "This will be shown in a popup."

MsgBoxreferenceif you are interested in going this route.

MsgBox引用如果你有兴趣在走这条路。

回答by Joey

First of all, DOS has nothing to do with it, you probably want a Windows command line solution (again: no DOS, pure Windows, just not a Window, but a Console).

首先,DOS与它无关,您可能需要Windows命令行解决方案(再次:没有DOS,纯Windows,只是不是Window,而是Console)。

You can either use the VBScript method provided by boflynn or you can mis-use net sendor msg. net sendworks only on older versions of windows:

您可以使用 boflynn 提供的 VBScript 方法,也可以误用net sendmsg. net send仅适用于旧版本的 Windows:

net send localhost Some message to display

This also depends on the Messenger service to run, though.

不过,这也取决于要运行的 Messenger 服务。

For newer versions (XP and onward, apparently):

对于较新版本(XP 及更高版本,显然):

msg "%username%" Some message to display

It should be noted that a message box sent using msg.exewill only last for 60 seconds. This can however be overridden with the /time:xxswitch.

需要注意的是,使用发送的消息框msg.exe只会持续 60 秒。然而,这可以被/time:xx开关覆盖。

回答by Fowl

Might display a little flash, but no temp files required. Should work all the way back to somewhere in the (IIRC) IE5 era.

可能会显示一点闪光,但不需要临时文件。应该一直工作到(IIRC)IE5 时代的某个地方。

mshta javascript:alert("Message\n\nMultiple\nLines\ntoo!");close();

Don't forget to escape your parenthesesif you're using if:

如果您正在使用,不要忘记转义括号if

if 1 == 1 (
   mshta javascript:alert^("1 is equal to 1, amazing."^);close^(^);
)

回答by Dave Webb

This will pop-up another Command Prompt window:

这将弹出另一个命令提示符窗口:

START CMD /C "ECHO My Popup Message && PAUSE"

回答by Dave Webb

Try :

尝试 :

Msg * "insert your message here" 

If you are using Windows XP's command.com, this will open a message box.

如果您使用的是 Windows XP 的 command.com,这将打开一个消息框。

Opening a new cmd window isn't quite what you were asking for, I gather. You could also use VBScript, and use this with your .bat file. You would open it from the bat file with this command:

我想,打开一个新的 cmd 窗口并不是您所要求的。您也可以使用VBScript,并将其与您的 .bat 文件一起使用。您可以使用以下命令从 bat 文件中打开它:

cd C:\"location of vbscript"

What this does is change the directory command.com will search for files from, then on the next line:

这样做是更改目录 command.com 将从中搜索文件,然后在下一行:

"insert name of your vbscript here".vbs

Then you create a new Notepaddocument, type in

然后你创建一个新的记事本文档,输入

<script type="text/vbscript">
    MsgBox "your text here"
</script>

You would then save this as a .vbs file (by putting ".vbs" at the end of the filename), save as "All Files" in the drop down box below the file name (so it doesn't save as .txt), then click Save!

然后将其保存为 .vbs 文件(通过将“.vbs”放在文件名的末尾),在文件名下方的下拉框中另存为“所有文件”(因此它不会另存为 .txt ),然后点击保存!

回答by npocmaka

Few more ways.

还有几个办法。

1)The geekiest and hackiest - it uses the IEXPRESS to create small exe that will create a pop-up with a single button (it can create two more types of pop-up messages). Works on EVERY windows from XP and above:

1)geekiest 和hackiest - 它使用 IEXPRESS 创建小 exe,该 exe 将创建一个带有单个按钮的弹出窗口(它可以创建另外两种类型的弹出消息)。适用于 XP 及更高版本的每个窗口:

;@echo off
;setlocal

;set ppopup_executable=popupe.exe
;set "message2=click OK to continue"
;
;del /q /f %tmp%\yes >nul 2>&1
;
;copy /y "%~f0" "%temp%\popup.sed" >nul 2>&1

;(echo(FinishMessage=%message2%)>>"%temp%\popup.sed";
;(echo(TargetName=%cd%\%ppopup_executable%)>>"%temp%\popup.sed";
;(echo(FriendlyName=%message1_title%)>>"%temp%\popup.sed"
;
;iexpress /n /q /m %temp%\popup.sed
;%ppopup_executable%
;rem del /q /f %ppopup_executable% >nul 2>&1

;pause

;endlocal
;exit /b 0


[Version]
Class=IEXPRESS
SEDVersion=3
[Options]
PackagePurpose=InstallApp
ShowInstallProgramWindow=1
HideExtractAnimation=1
UseLongFileName=0
InsideCompressed=0
CAB_FixedSize=0
CAB_ResvCodeSigning=0
RebootMode=N
InstallPrompt=%InstallPrompt%
DisplayLicense=%DisplayLicense%
FinishMessage=%FinishMessage%
TargetName=%TargetName%
FriendlyName=%FriendlyName%
AppLaunched=%AppLaunched%
PostInstallCmd=%PostInstallCmd%
AdminQuietInstCmd=%AdminQuietInstCmd%
UserQuietInstCmd=%UserQuietInstCmd%
SourceFiles=SourceFiles
[SourceFiles]
SourceFiles0=C:\Windows\System32\
[SourceFiles0]
%FILE0%=


[Strings]
AppLaunched=subst.exe
PostInstallCmd=<None>
AdminQuietInstCmd=
UserQuietInstCmd=
FILE0="subst.exe"
DisplayLicense=
InstallPrompt=

2)Using MSHTA. Also works on every windows machine from XP and above (despite the OP do not want "external" languages the JavaScript here is minimized). Should be saved as .bat:

2)使用MSHTA。也适用于 XP 及更高版本的每台 Windows 机器(尽管 OP 不想要“外部”语言,但此处的 JavaScript 已最小化)。应另存为.bat

@if (true == false) @end /*!
@echo off
mshta "about:<script src='file://%~f0'></script><script>close()</script>" %*
goto :EOF */

alert("Hello, world!");

or in one line:

或在一行中:

mshta "about:<script>alert('Hello, world!');close()</script>"

or

或者

mshta "javascript:alert('message');close()"

or

或者

mshta.exe vbscript:Execute("msgbox ""message"",0,""title"":close")

3)Here's parameterized .bat/jscripthybrid (should be saved as bat). It again uses JavaScript despite the OP request but as it is a bat it can be called as a bat file without worries. It uses POPUPwhich allows a little bit more control than the more popular MSGBOX. It uses WSH, but not MSHTA like in the example above.

3)这里是参数.bat/jscript化的混合(应该另存为bat)。尽管有 OP 请求,它再次使用 JavaScript,但由于它是 bat,因此可以毫无顾虑地将其称为 bat 文件。它使用POPUP允许比更流行的MSGBOX多一点控制。它使用 WSH,但不像上面的例子那样使用 MSHTA。

 @if (@x)==(@y) @end /***** jscript comment ******
     @echo off

     cscript //E:JScript //nologo "%~f0" "%~nx0" %*
     exit /b 0

 @if (@x)==(@y) @end ******  end comment *********/


var wshShell = WScript.CreateObject("WScript.Shell");
var args=WScript.Arguments;
var title=args.Item(0);

var timeout=-1;
var pressed_message="button pressed";
var timeout_message="timed out";
var message="";

function printHelp() {
    WScript.Echo(title + "[-title Title] [-timeout m] [-tom \"Time-out message\"] [-pbm \"Pressed button message\"]  [-message \"pop-up message\"]");
}

if (WScript.Arguments.Length==1){
    runPopup();
    WScript.Quit(0);
}

if (args.Item(1).toLowerCase() == "-help" || args.Item(1).toLowerCase() == "-h" ) {
    printHelp();
    WScript.Quit(0);
}

if (WScript.Arguments.Length % 2 == 0 ) {
    WScript.Echo("Illegal arguments ");
    printHelp();
    WScript.Quit(1);
}

for (var arg = 1 ; arg<args.Length;arg=arg+2) {

    if (args.Item(arg).toLowerCase() == "-title") {
        title = args.Item(arg+1);
    }

    if (args.Item(arg).toLowerCase() == "-timeout") {
        timeout = parseInt(args.Item(arg+1));
        if (isNaN(timeout)) {
            timeout=-1;
        }
    }

    if (args.Item(arg).toLowerCase() == "-tom") {
        timeout_message = args.Item(arg+1);
    }

    if (args.Item(arg).toLowerCase() == "-pbm") {
        pressed_message = args.Item(arg+1);
    }

    if (args.Item(arg).toLowerCase() == "-message") {
        message = args.Item(arg+1);
    }
}

function runPopup(){
    var btn = wshShell.Popup(message, timeout, title, 0x0 + 0x10);

    switch(btn) {
        // button pressed.
        case 1:
            WScript.Echo(pressed_message);
            break;

        // Timed out.
        case -1:
           WScript.Echo(timeout_message);
           break;
    }
}

runPopup();

4)and one jscript.net/.bathybrid (should be saved as .bat) .This time it uses .NETand compiles a small .exefile that could be deleted:

4)和一个 jscript.net/.bat混合(应该另存为.bat)。这次它使用.NET并编译了一个.exe可以删除的小文件:

@if (@X)==(@Y) @end /****** silent jscript comment ******

@echo off
::::::::::::::::::::::::::::::::::::
:::       compile the script    ::::
::::::::::::::::::::::::::::::::::::
setlocal


::if exist "%~n0.exe" goto :skip_compilation

:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
    if exist "%%v\jsc.exe" (
        rem :: the javascript.net compiler
        set "jsc=%%~dpsnfxv\jsc.exe"
        goto :break_loop
    )
)
echo jsc.exe not found && exit /b 0
:break_loop



call %jsc% /nologo /out:"%~n0.exe" "%~f0" 
::::::::::::::::::::::::::::::::::::
:::       end of compilation    ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation

::
::::::::::
"%~n0.exe" %*
::::::::
::
endlocal
exit /b 0

****** end of jscript comment ******/

import System;
import System.Windows;
import System.Windows.Forms

var arguments:String[] = Environment.GetCommandLineArgs();
MessageBox.Show(arguments[1],arguments[0]);

5)and at the end one single call to powershell that creates a pop-up (can be called from command line or from batch if powershell is installed):

5)最后一次调用powershell创建一个弹出窗口(如果安装了powershell,可以从命令行或批处理调用):

powershell [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""Hello World""", """My PopUp Message Box""")

6)And the dbenham's approach seen here

6)这里看到的dbenham的方法

start "" cmd /c "echo(&echo(&echo              Hello world!     &echo(&pause>nul"

7) For a system tray notifications you can try this:

7)对于系统托盘通知,你可以试试这个

call SystemTrayNotification.bat  -tooltip warning -time 3000 -title "Woow" -text "Boom" -icon question

回答by dc1

This way your batch file will create a VBS script and show a popup. After it runs, the batch file will delete that intermediate file.

这样您的批处理文件将创建一个 VBS 脚本并显示一个弹出窗口。运行后,批处理文件将删除该中间文件。

The advantage of using MSGBOX is that it is really customaziable (change the title, the icon etc) while MSG.exe isn't as much.

使用 MSGBOX 的优点是它确实是可定制的(更改标题、图标等),而 MSG.exe 则没有那么多。

echo MSGBOX "YOUR MESSAGE" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q

回答by User5910

Here's a PowerShell variant that doesn't require loading assemblies prior to creating the window, however it runs noticeably slower (~+50%) than the PowerShell MessageBox command posted here by @npocmaka:

这是一个 PowerShell 变体,它不需要在创建窗口之前加载程序集,但是它的运行速度明显比@npocmaka 在此处发布的 PowerShell MessageBox 命令慢(~+50%):

powershell (New-Object -ComObject Wscript.Shell).Popup("""Operation Completed""",0,"""Done""",0x0)

You can change the last parameter from "0x0" to a value below to display icons in the dialog (see Popup Methodfor further reference):

您可以将最后一个参数从“0x0”更改为下面的值以在对话框中显示图标(请参阅弹出方法以获取更多参考):

        Stop0x10 Stop
        Question Mark0x20 Question Mark
        Exclamation Mark0x30 Exclamation Mark
        Information Mark0x40 Information Mark

        停止0x10 停止
        问号0x20 问号
        感叹号0x30 感叹号
        Information Mark0x40 信息标记

Adapted from the Microsoft TechNet article PowerTip: Use PowerShell to Display Pop-Up Window.

改编自 Microsoft TechNet 文章PowerTip:使用 PowerShell 显示弹出窗口

回答by p2013

echo X=MsgBox("Message Description",0+16,"Title") >msg.vbs

–you can write any numbers from 0,1,2,3,4 instead of 0 (before the ‘+' symbol) & here is the meaning of each number:

– 你可以写 0,1,2,3,4 中的任何数字而不是 0(在“+”符号之前)&这里是每个数字的含义:

0 = Ok Button  
1 = Ok/Cancel Button  
2 = Abort/Retry/Ignore button  
3 = Yes/No/Cancel  
4 = Yes/No  

–you can write any numbers from 16,32,48,64 instead of 16 (after the ‘+' symbol) & here is the meaning of each number:

– 您可以写出 16,32,48,64 中的任何数字,而不是 16(在“+”符号之后)&这里是每个数字的含义:

16 – Critical Icon  
32 – Warning Icon  
48 – Warning Message Icon   
64 – Information Icon  

回答by Max Runacres

Msg * "insert your message here"

Msg * "在此处插入您的消息"

works fine, just save as a .bat file in notepad or make sure the format is set to "all files"

工作正常,只需在记事本中另存为 .bat 文件或确保格式设置为“所有文件”