【发布时间】:2014-09-28 19:17:05
【问题描述】:
我想知道是否有人可以提供有关 Windows Shell 如何传递的链接或解释,例如,默认应用程序、Internet Explorer、Google Chrome 的 URL 或自定义构建应用程序的参数。
我看过类似的例子:Run shell commands using c# and get the info into string
上述链接和其他类似链接的问题是它们没有按预期工作还是没有真正回答实际问题。比如……
此代码按预期工作:
private string EXEPath = @"C:\Program Files (x86)\Internet Explorer\iexplore.exe";
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = EXEPath,
Arguments = "http://www.google.com.au",
UseShellExecute = true,
RedirectStandardOutput = false,
CreateNoWindow = true
}
};
process.Start();
此链接提供了如何将应用程序设置为单实例应用程序的一个很好的示例:http://social.msdn.microsoft.com/Forums/vstudio/en-US/a5bcfc8a-bf69-4bbc-923d-f30f9ecf5f64/single-instance-application
像这样处理参数:
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));
}
然后在 Form1 中像这样处理参数:
private string[] Args;
public MINION(string[] args)
{
InitializeComponent();
// Assign the incoming Arguments...
this.AppArgs = args;
}
public string[] AppArgs
{
set
{
this.Args = value;
if (this.Args.Length > 0)
{
foreach (string arg in this.Args)
{
// Do the processing here of each arg...
}
}
}
}
我正在使用单击一次。我在上面的链接中设置了带有 VB 单实例代码的应用程序。此代码有效,并且只有一个应用程序实例运行。
我的问题:
如果我将参数传递给我的应用程序,测试会显示进程 ID 与正在运行的实例的进程 ID 不同。从而表明已经运行的 Application 的实例不是 Args 通过代码传递给的实例:
private string EXEPath = @"C:\Program Files (x86)\My App\My App.exe"; // Or actual path to EXE.
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = EXEPath,
Arguments = "http://www.google.com.au",
UseShellExecute = true,
RedirectStandardOutput = false,
CreateNoWindow = true
}
};
process.Start();
因此,即使代码已将应用程序设置为单实例应用程序,此代码也会启动一个新实例。正在运行的现有应用程序实例不会处理传递的参数。
新实例将显示一个编码消息框(“我已经运行...”),但之后退出。
编辑 @loopedcode - 第一个答案。这是我用来确保我始终与同一个 EXE 对话的代码。这也是一种享受。很遗憾,我已经涵盖了您的建议。
Process[] runningProcess = Process.GetProcessesByName("MyEXEName.exe");
Process proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = runningProcess[0].MainModule.FileName,
Arguments = "http://www.google.com.au",
UseShellExecute = true,
RedirectStandardOutput = false,
CreateNoWindow = true
}
};
proc.Start();
我可以验证完全相同的路径对于正在运行的实例以及对 EXE 路径的 Shell 调用有效。
编辑 - 11.08.14
我想稍微扩展一下这个问题。
当传递参数时,我一直到处理新进程 ID 中的参数,然后将实例切换到单实例应用程序回到现有实例的代码启动。在这个阶段,参数是未传递给现有实例。
如果我使用:
MessageBox.Show("Program ID: " + (Process.GetCurrentProcess().Id) + " Arg Passed: " + this.Args[0]);
它在新实例上运行,但不在现有实例上。
【问题讨论】: