【发布时间】:2013-07-26 03:31:57
【问题描述】:
我有一个 WinForm 应用程序,它将一种文件格式转换为另一种文件格式。
我想添加 CLI 支持,因此我正在使用 WindowsForms 中的 CMD。
如果从 CMD 调用应用程序,则该 CMD 将附加到 APP 并且不显示 GUI。
我的应用程序先检测文件格式,然后什么都不做。
问题是,例如,如果我运行此批处理命令,则文件将被删除,因为我没有发送错误代码:
MyApp.exe "File With Incorrec tFormat" && Del "File With Incorrect Format"
PS:“&&”批处理运算符用于检查前面命令的%ERRORLEVEL%是否为“0”以继续执行命令连接。
我想避免使用我的应用时的风险。
那么当我的应用检测到文件格式不正确时,如何向附加的 CMD 发送非零退出代码?
PS:我不知道我需要的是发送非零退出代码还是需要做其他事情。
这是过程:
' Parse Arguments
Private Sub Parse_Arguments()
If My.Application.CommandLineArgs.Count <> 0 Then NativeMethods.AttachConsole(-1) Else Exit Sub
Dim File As String = My.Application.CommandLineArgs.Item(0).ToLower
If IO.File.Exists(File) Then
If Not IsRegFile(File) Then
Console.WriteLine("ERROR: " & "" & File & "" & " is not a valid Regedit v5.00 script.")
End
End If
Dim fileinfo As New IO.FileInfo(File)
If My.Application.CommandLineArgs.Count = 1 Then
Try
IO.File.WriteAllText(fileinfo.DirectoryName & ".\" & fileinfo.Name.Substring(0, fileinfo.Name.LastIndexOf(".")) & ".bat", Reg2Bat(File), System.Text.Encoding.Default)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Else
Try
IO.File.WriteAllText(My.Application.CommandLineArgs.Item(1), Reg2Bat(File), System.Text.Encoding.Default)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End If ' My.Application.CommandLineArgs.Count = 1
' Console.WriteLine("Done!")
Else
Console.WriteLine("ERROR: " & "" & File & "" & " don't exists.")
End If ' IO.File.Exists
End
End Sub
更新:
另一个更具体地说明我正在尝试做的例子...:
Public Class Form1
<System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError:=True)> _
Private Shared Function AttachConsole(dwProcessId As Int32) As Boolean
End Function
Private Shared Function SendExitCode(ByVal ExitCode As Int32) As Int32
' Here will goes unknown stuff to set the attached console exitcode...
Console.WriteLine(String.Format("Expected ExitCode: {0}", ExitCode))
Return ExitCode
End Function
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
AttachConsole(-1) ' Attaches the console.
SendExitCode(2) ' Send the exitcode (2) to the attached console.
Application.Exit() ' ...And finally close the app.
End Sub
End Class
我该怎么做?
【问题讨论】:
标签: vb.net winforms cmd console-application exit-code