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

时间:2009-04-21 19:21:54

标签: windows batch-file command-line messagebox

有没有办法从批处理文件中显示消息框(类似于Linux中bash-scripts可以使用xmessage的方式)?

21 个答案:

答案 0 :(得分:119)

首先,DOS与它无关,你可能想要一个Windows命令行解决方案(再次:没有DOS,纯Windows,不是一个窗口,而是一个控制台)。

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

net send localhost Some message to display

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

对于较新版本(XP及以后,显然):

msg "%username%" Some message to display

应该注意,使用msg.exe发送的消息框只能持续60秒。但是,可以使用/time:xx开关覆盖此内容。

答案 1 :(得分:109)

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

保存在MessageBox.vbs中的以下内容:

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

您可以这样称呼:

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

MsgBox reference如果你有兴趣走这条路。

答案 2 :(得分:83)

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

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

如果您使用的是if,请不要忘记escape your parentheses

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

答案 3 :(得分:69)

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

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

答案 4 :(得分:33)

尝试:

Msg * "insert your message here" 

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

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

cd C:\"location of vbscript"

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

"insert name of your vbscript here".vbs

然后您创建一个新的Notepad文档,输入

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

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

答案 5 :(得分:26)

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

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

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

答案 6 :(得分:26)

更多方法。

1)最怪异和最黑客 - 它使用IEXPRESS创建小型exe,它将使用单个按钮(it can create two more types of pop-up messages)创建弹出窗口。适用于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)使用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!");

或一行:

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

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

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

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)和一个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)最后一次调用powershell创建一个弹出窗口(如果安装了powershell,可以从命令行调用或从批处理调用):

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

6) dbenham的做法见here

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

7 )对于系统托盘通知,您可以尝试this

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

答案 7 :(得分:10)

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

- 你可以写出0,1,2,3,4中的任何数字而不是0(在'+'符号之前)&amp;这是每个数字的含义:

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

- 你可以写出16,32,48,64而不是16(在'+'符号后面)的任何数字。这是每个数字的含义:

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

答案 8 :(得分:9)

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

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

您可以将最后一个参数从“0x0”更改为下面的值,以在对话框中显示图标(有关详细信息,请参阅Popup Method):

Stop 0x10停止
Question Mark 0x20问号 Exclamation Mark 0x30感叹号
Information Mark 0x40信息标记

改编自Microsoft TechNet文章PowerTip: Use PowerShell to Display Pop-Up Window

答案 9 :(得分:7)

消息*&#34;在此处插入您的消息&#34;

工作正常,只需在记事本中保存为.bat文件,或确保格式设置为&#34;所有文件&#34;

答案 10 :(得分:4)

为了做到这一点,你需要一个小程序来显示一个消息框并从你的批处理文件中运行它。

您可以打开一个显示提示的控制台窗口,但是不能使用cmd.exe和朋友获取GUI消息框,AFAIK。

答案 11 :(得分:3)

我从这里使用名为msgbox.exe的实用程序: http://www.paulsadowski.com/WSH/cmdprogs.htm

答案 12 :(得分:3)

您可以使用Zenity。 Zenity允许在命令行和shell脚本中执行对话框。更多信息也可以在Wikipedia找到。

它是跨平台的:可以找到Windows的Windows安装程序here

答案 13 :(得分:3)

msg * /time:0 /w Hello everybody!

此消息将一直等待,直到单击确定(默认情况下仅持续一分钟)并在Windows 8.1中正常工作

答案 14 :(得分:2)

根据@ Fowl的回答,您可以使用以下内容将超时提升为10秒:

mshta "javascript:var sh=new ActiveXObject( 'WScript.Shell' ); sh.Popup( 'Message!', 10, 'Title!', 64 );close()"

有关详细信息,请参阅here

答案 15 :(得分:2)

我认为你可以从user32.dll调用dll函数 像

这样的东西
  

Rundll32.exe user32.dll,MessageBox(0,&#34; text&#34;,&#34; titleText&#34;,{for topmost messagebox e.t.c的额外标志}}

从我的手机输入,不要判断我...否则我会链接额外的标志。

答案 16 :(得分:1)

msg * /server:127.0.0.1在此输入您的留言

答案 17 :(得分:1)

如果您将批处理文件转换(换行)为可执行文件,则此application可以执行此操作。

  1. 简单邮箱

    %extd% /messagebox Title Text
    
    1. 错误消息框

      %extd% /messagebox  Error "Error message" 16
      
    2. 取消再试一次Messagebox

      %extd% /messagebox Title "Try again or Cancel" 5
      
    3. 4)“再也不要问我了”Messagebox

      %extd% /messageboxcheck Title Message 0 {73E8105A-7AD2-4335-B694-94F837A38E79}
      

答案 18 :(得分:0)

更好的选择

<强> set my_message=Hello world && start cmd /c "@echo off & mode con cols=15 lines=2 & echo %my_message% & pause>nul"

描述:
lines=行数量加1 邮件中cols=个字符数加上3(但最小值必须为15

自动计算cols版本:

<强> set my_message=Hello world && (echo %my_message%>EMPTY_FILE123 && FOR %? IN (EMPTY_FILE123 ) DO SET strlength=%~z? && del EMPTY_FILE123 ) && start cmd /c "@echo off && mode con lines=2 cols=%strlength% && echo %my_message% && pause>nul"

答案 19 :(得分:0)

这是我根据此处和其他帖子的好答案整理的批处理脚本

您可以设置标题超时,甚至可以休眠以将其安排在后面,而\ n安排在新行

将其命名为popup.bat并将其放在Windows路径文件夹中,以在您的PC上全局工作

例如popup Line 1\nLine 2将产生一个2行弹出框 (键入popup /?以供使用)

这是代码

<!-- : Begin CMD
@echo off
cscript //nologo "%~f0?.wsf" %*
set pop.key=[%errorlevel%]
if %pop.key% == [-1] set pop.key=TimedOut
if %pop.key% == [1]  set pop.key=Ok
if %pop.key% == [2]  set pop.key=Cancel
if %pop.key% == [3]  set pop.key=Abort
if %pop.key% == [4]  set pop.key=Retry
if %pop.key% == [5]  set pop.key=Ignore
if %pop.key% == [6]  set pop.key=Yes
if %pop.key% == [7]  set pop.key=No
if %pop.key% == [10] set pop.key=TryAgain
if %pop.key% == [11] set pop.key=Continue
if %pop.key% == [99] set pop.key=NoWait
exit /b 
-- End CMD -->

<job><script language="VBScript">
'on error resume next
q   =""""
qsq =""" """
Set objArgs = WScript.Arguments
Set objShell= WScript.CreateObject("WScript.Shell")
Popup       =   0
Title       =   "Popup"
Timeout     =   0
Mode        =   0
Message     =   ""
Sleep       =   0
button      =   0
If objArgs.Count = 0 Then 
    Usage()
ElseIf objArgs(0) = "/?" or Lcase(objArgs(0)) = "-h" or Lcase(objArgs(0)) = "--help" Then 
    Usage()
End If
noWait = Not wait() 
For Each arg in objArgs
    If (Mid(arg,1,1) = "/") and (InStr(arg,":") <> 0) Then haveSwitch   =   True
Next
If not haveSwitch Then 
    Message=joinParam("woq")
Else
    For i = 0 To objArgs.Count-1 
        If IsSwitch(objArgs(i)) Then 
            S=split(objArgs(i) , ":" , 2)
                select case Lcase(S(0))
                    case "/m","/message"
                        Message=S(1)
                    case "/tt","/title"
                        Title=S(1)
                    case "/s","/sleep"
                        If IsNumeric(S(1)) Then Sleep=S(1)*1000
                    case "/t","/time"
                        If IsNumeric(S(1)) Then Timeout=S(1)
                    case "/b","/button"
                        select case S(1)
                            case "oc", "1"
                                button=1
                            case "ari","2"
                                button=2
                            case "ync","3"
                                button=3
                            case "yn", "4"
                                button=4
                            case "rc", "5"
                                button=5
                            case "ctc","6"
                                button=6
                            case Else
                                button=0
                        end select
                    case "/i","/icon"
                        select case S(1)
                            case "s","x","stop","16"
                                Mode=16
                            case "?","q","question","32"
                                Mode=32
                            case "!","w","warning","exclamation","48"
                                Mode=48
                            case "i","information","info","64"
                                Mode=64
                            case Else 
                                Mode=0
                        end select
                end select
        End If
    Next
End If
Message = Replace(Message,"/\n", "°"  )
Message = Replace(Message,"\n",vbCrLf)
Message = Replace(Message, "°" , "\n")
If noWait Then button=0

Wscript.Sleep(sleep)
Popup   = objShell.Popup(Message, Timeout, Title, button + Mode + vbSystemModal)
Wscript.Quit Popup

Function IsSwitch(Val)
    IsSwitch        = False
    If Mid(Val,1,1) = "/" Then
        For ii = 3 To 9 
            If Mid(Val,ii,1)    = ":" Then IsSwitch = True
        Next
    End If
End Function

Function joinParam(quotes)
    ReDim ArgArr(objArgs.Count-1)
    For i = 0 To objArgs.Count-1 
        If quotes = "wq" Then 
            ArgArr(i) = q & objArgs(i) & q 
        Else
            ArgArr(i) =     objArgs(i)
        End If
    Next
    joinParam = Join(ArgArr)
End Function

Function wait()
    wait=True
    If objArgs.Named.Exists("NewProcess") Then
        wait=False
        Exit Function
    ElseIf objArgs.Named.Exists("NW") or objArgs.Named.Exists("NoWait") Then
        objShell.Exec q & WScript.FullName & qsq & WScript.ScriptFullName & q & " /NewProcess: " & joinParam("wq") 
        WScript.Quit 99
    End If
End Function

Function Usage()
    Wscript.Echo _
                     vbCrLf&"Usage:" _
                    &vbCrLf&"      popup followed by your message. Example: ""popup First line\nescaped /\n\nSecond line"" " _
                    &vbCrLf&"      To triger a new line use ""\n"" within the msg string [to escape enter ""/"" before ""\n""]" _
                    &vbCrLf&"" _
                    &vbCrLf&"Advanced user" _
                    &vbCrLf&"      If any Switch is used then you must use the /m: switch for the message " _
                    &vbCrLf&"      No space allowed between the switch & the value " _
                    &vbCrLf&"      The switches are NOT case sensitive " _
                    &vbCrLf&"" _
                    &vbCrLf&"      popup [/m:""*""] [/t:*] [/tt:*] [/s:*] [/nw] [/i:*]" _
                    &vbCrLf&"" _
                    &vbCrLf&"      Switch       | value |Description" _
                    &vbCrLf&"      -----------------------------------------------------------------------" _
                    &vbCrLf&"      /m: /message:| ""1 2"" |if the message have spaces you need to quote it " _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /t: /time:   | nn    |Duration of the popup for n seconds " _
                    &vbCrLf&"                   |       |<Default> untill key pressed" _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /tt: /title: | ""A B"" |if the title have spaces you need to quote it " _
                    &vbCrLf&"                   |       | <Default> Popup" _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /s: /sleep:  | nn    |schedule the popup after n seconds " _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /nw /NoWait  |       |Continue script without the user pressing ok - " _
                    &vbCrLf&"                   |       | botton option will be defaulted to OK button " _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /i: /icon:   | ?/q   |[question mark]"  _
                    &vbCrLf&"                   | !/w   |[exclamation (warning) mark]"  _
                    &vbCrLf&"                   | i/info|[information mark]"  _
                    &vbCrLf&"                   | x/stop|[stop\error mark]" _
                    &vbCrLf&"                   | n/none|<Default>" _
                    &vbCrLf&"                   |       |" _
                    &vbCrLf&"      /b: /button: | o     |[OK button] <Default>"  _
                    &vbCrLf&"                   | oc    |[OK and Cancel buttons]"  _
                    &vbCrLf&"                   | ari   |[Abort, Retry, and Ignore buttons]"  _
                    &vbCrLf&"                   | ync   |[Yes, No, and Cancel buttons]" _
                    &vbCrLf&"                   | yn    |[Yes and No buttons]" _
                    &vbCrLf&"                   | rc    |[Retry and Cancel buttons]" _
                    &vbCrLf&"                   | ctc   |[Cancel and Try Again and Continue buttons]" _
                    &vbCrLf&"      --->         | --->  |The output will be saved in variable ""pop.key""" _
                    &vbCrLf&"" _
                    &vbCrLf&"Example:" _
                    &vbCrLf&"        popup /tt:""My MessageBox"" /t:5 /m:""Line 1\nLine 2\n/\n\nLine 4""" _
                    &vbCrLf&"" _
                    &vbCrLf&"                     v1.9 By RDR @ 2020"
    Wscript.Quit
End Function

</script></job>

答案 20 :(得分:-3)

它只需要在vm内弹出,所以从技术上讲,应该有一些代码:

if %machine_type% == virtual_machine then
   echo message box code
else
   continue normal installation code