从一个WinForm发送ExitCode到附加的CMD?

时间:2013-07-26 03:31:57

标签: vb.net winforms cmd console-application exit-code

我有一个WinForm应用程序,它包含将一种文件格式转换为其他文件格式。

我想添加CLI支持,所以我正在使用WindowsForms中的CMD。

如果从CMD调用该应用程序,则该CMD将附加到APP,并且不会显示GUI。

我的应用程序检测到什么都不做的文件格式第一。

问题是,例如,如果我运行此Batch命令,那么文件将被删除,因为我没有发送错误代码:

MyApp.exe "File With Incorrec tFormat" && Del "File With Incorrect Format"

PS:“&&”批处理运算符用于检查before命令的%ERRORLEVEL%是否为“0”以继续执行命令连接。

我想避免使用我的应用程序时的风险。

那么当我的应用程序检测到文件格式不正确时,如何向附加的CMD发送非零exitcode? PS:我不知道我需要的是发送非零exitcode还是我需要做其他事情。

这是proc:

' 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

我怎么做?。

2 个答案:

答案 0 :(得分:2)

您需要将您的应用程序编译为控制台应用程序(即使您没有从命令行调用时启动的GUI),也可以使用main方法返回int或调用environment.exit(-1)

答案 1 :(得分:2)

如果我理解你的问题,下面的代码应该这样做。您可以从批处理文件调用GUI应用程序,附加到(通过CMD进程的)父控制台并向其返回退出代码。

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace TestApp
{
    static class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AttachConsole(uint dwProcessId);
        const uint ATTACH_PARENT_PROCESS = uint.MaxValue;

        // The main entry point for the application.
        [STAThread]
        static int Main(string[] args)
        {
            if (args.Length < 1)
                return 1;

            int exitCode = 0;
            int.TryParse(args[0], out exitCode);
            var message = String.Format("argument: {0}", exitCode);

            if (args.Length > 1 && args[1] == "-attach")
                AttachConsole(ATTACH_PARENT_PROCESS);

            Console.WriteLine(message); // do the console output 
            MessageBox.Show(message); // do the UI

            return exitCode;
        }
    }
}

这是一个测试批处理文件:

@echo off
TestApp.exe 1 -attach && echo success
echo exit code: %errorlevel%

输出:

argument: 1
exit code: 1

批处理文件中将“1”更改为“0”,输出为:

argument: 0
success
exit code: 0

希望这有帮助。

<强>更新

在更新的VB代码中,您可能需要在退出应用之前设置Environment.ExitCode

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))

    Environment.ExitCode = ExitCode

    Return ExitCode
End Function