指定应用程序退出时的返回错误代码
Posted
技术标签:
【中文标题】指定应用程序退出时的返回错误代码【英文标题】:Specifying the Return Error Code on Application Exit 【发布时间】:2010-07-08 15:01:07 【问题描述】:如何在应用程序退出时指定返回错误代码?如果这是一个 VC++ 应用程序,我可以使用 SetLastError(ERROR_ACCESS_DENIED)
-- return GetLastError()
API。有没有办法在 C# 中做到这一点?
static int Main(string[] args)
Tool.Args = args;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Download_Tool());
return Tool.ErrorCode;
Tool.ErrorCode
值如何设置得通俗易懂?如果我尝试Tool.ErrorCode = ERROR_ACCESS_DENIED
之类的操作,我会收到错误消息,“当前上下文中不存在名称 ERROR_ACCESS_DENIED。”谢谢。
附加信息
我的例子过于简单化了。有没有办法像这样:
Tool.ErrorCode = ERROR_ACCESS_DENIED;
return Tool.ErrorCode;
...生成编译错误,而不是这样:
Tool.ErrorCode = 5;
return Tool.ErrorCode;
...有效,但使用“幻数”。我想避免使用幻数。
【问题讨论】:
【参考方案1】:http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx
Environment.Exit(exitCode)
更新
您收到带有“ERROR_ACCESS_DENIED”的编译错误的原因是您没有定义它。你需要自己定义:
const int ERROR_ACCESS_DENIED = 5;
那么你可以使用:
Environment.Exit(ERROR_ACCESS_DENIED)
更新 2
如果您正在为您的 C# 需求寻找一***成的 winerror.h 常量,那么这里是:
http://www.pinvoke.net/default.aspx/Constants/WINERROR.html
我可能会修改 GetErrorName(...) 方法来做一些缓存,例如:
private static Dictionary<int, string> _FieldLookup;
public static bool TryGetErrorName(int result, out string errorName)
if (_FieldLookup == null)
Dictionary<int, string> tmpLookup = new Dictionary<int, string>();
FieldInfo[] fields = typeof(ResultWin32).GetFields();
foreach (FieldInfo field in fields)
int errorCode = (int)field.GetValue(null);
tmpLookup.Add(errorCode, field.Name);
_FieldLookup = tmpLookup;
return _FieldLookup.TryGetValue(result, out errorName);
【讨论】:
这并没有解决使用幻数设置退出码的问题。 我想知道为什么这被否决了。希望不是在问题更新之后。我不是读心术……那太可怜了。 微软已经在某处定义了这些错误代码。在 VC++ 应用程序中,它们可以通过#include "Winerror.h"
访问。 C#没有类似的东西吗? msdn.microsoft.com/en-us/library/ms681381(VS.85).aspx
@Jim 据我所知,没有。过去在执行 PInvoke 时,我只是简单地获取头文件并将常量提取到 C# 帮助器类中以获得您所追求的奇偶校验。 not Win32 中的 C#。
@Jim 我已更新答案以包含指向具有所有 winerror.h 常量的类的 C# 代码的链接。 HTH。【参考方案2】:
设置Environment.ExitCode
。
static void Main(string[] args)
Tool.Args = args;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Download_Tool());
Environment.ExitCode = Tool.ErrorCode;
见MSDN - Environment.ExitCode Property
【讨论】:
这并没有解决使用幻数设置退出码的问题。 这段代码 sn-p 的问题是,如果Main
方法返回 void 以外的任何值(即本例中的 int
),则忽略 Environment.ExitCode
的值。
我把代码sn-p改成返回void,这样Environment.ExitCode就不会被忽略了。以上是关于指定应用程序退出时的返回错误代码的主要内容,如果未能解决你的问题,请参考以下文章
Xamarin 无法构建到设备 - 工具退出,代码:1。输出:错误:在钥匙串中找不到指定的项目