创建一个可以打开应用程序的Windows c#应用程序
本文关键字:应用程序 Windows 一个 创建 | 更新日期: 2023-09-27 18:15:50
我最近有了一个想法,创建一个c# Windows窗体应用程序,使用户能够从那里启动应用程序。这是我的"原始"代码:
按钮1单击"事件…"
{
System.Diagnostics.Process.Start("WINWORD.EXE");
}
按钮2单击"事件…"
{
System.Diagnostics.Process.Start("WINRAR.EXE");
}
。.....
和更多…
谁能告诉我什么代码是在处理事件的情况下,一个应用程序找不到(例如)。WINWORD.EXE不可用等等,等等)?
我尝试使用'if-statement',但无济于事,我得到编译错误。
有人能帮我一下吗?我如何创建一个函数,让用户添加一些应用程序的快捷方式到c#应用程序?提前感谢大家
System.IO.File.Exists("your file path");
如果文件存在
返回trueif(System.IO.File.Exists("your file path"))
{
//Do something
}
else
{
OpenFileDialog _File = new OpenFileDialog())
_File.ShowDialog(); // this will open a filedialog box to browse
}
使用System.IO.File.Exists
验证文件路径或使用try..catch..
块处理异常
try
{
System.Diagnostics.Process.Start("WINWORD.EXE");
}catch(Exception ex)
{
MessageBox.Show(ex.getMessage());
}
我将把启动应用程序的调用放在try...catch...
块中
按钮2单击"事件…"
{
try
{
System.Diagnostics.Process.Start("WINRAR.EXE");
}
catch(Exception exc)
{
// handle exception, e.g. possibly log it to a file or database, or do something else
MessageBox.Show(exc.Message, "Error occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
在这种情况下,无论出现什么问题,您都能够捕捉到这种情况,并至少向用户显示一条消息—当然,您可能需要稍微"调整"一下该消息.....
最好"三思而后行",检查系统的PATH
和文件的系统注册表—但是这比看起来要困难得多。例如,在我的PC上,通过路径找不到Microsoft Office。
最简单的是检查System.ComponentModel.Win32Exception
:
try
{
Process.Start("filename.exe");
}
catch (System.ComponentModel.Win32Exception ex)
{
if (ex.NativeErrorCode == 2)
{
// file was not found, so do something
}
}
通过显式检查正确的底层异常,您可以确保系统在发生除文件未找到以外的情况时仍然停止。此外,通过检查错误代码2,您知道您的系统应该在使用英语以外的其他语言的Windows版本上工作。