【发布时间】:2010-08-20 01:21:23
【问题描述】:
如何判断用户是否通过双击 EXE(或快捷方式)启动了我的控制台应用程序,或者他们是否已经打开了命令行窗口并在该会话中执行了我的控制台应用程序?
【问题讨论】:
标签: c# .net command-line console console-application
如何判断用户是否通过双击 EXE(或快捷方式)启动了我的控制台应用程序,或者他们是否已经打开了命令行窗口并在该会话中执行了我的控制台应用程序?
【问题讨论】:
标签: c# .net command-line console console-application
将此静态字段粘贴到您的“Program”类中,以确保它在任何输出之前运行:
static bool StartedFromGui =
!Console.IsOutputRedirected
&& !Console.IsInputRedirected
&& !Console.IsErrorRedirected
&& Environment.UserInteractive
&& Environment.CurrentDirectory == System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
&& Console.CursorTop == 0 && Console.CursorLeft == 0
&& Console.Title == Environment.GetCommandLineArgs()[0]
&& Environment.GetCommandLineArgs()[0] == System.Reflection.Assembly.GetEntryAssembly().Location;
这有点矫枉过正/偏执,但从资源管理器开始,而不响应cls && app.exe(通过检查完整路径)甚至cls && "f:\ull\path\to\app.exe"(通过查看标题)之类的东西。
我从win32 version of this question 得到这个想法。
【讨论】:
static bool startedFromVisualStudio = !Console.IsOutputRedirected && !Console.IsInputRedirected && !Console.IsErrorRedirected && Environment.UserInteractive && Environment.CurrentDirectory == System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) && Console.CursorTop == 0 && Console.CursorLeft == 0 && Environment.GetCommandLineArgs()[0].Contains("vshost"); 从 VS 启动时也等待按键
您也许可以通过 P/Invoking Win32 GetStartupInfo() 函数来解决这个问题。
[DllImport("kernel32", CharSet=CharSet.Auto)]
internal static extern void GetStartupInfo([In, Out] STARTUPINFO lpStartupInfo);
【讨论】:
你可以找出父进程是什么:
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess()?.Parent()?.ProcessName);
其中 Parent() 是一个扩展方法,例如:
public static class Extensions
{
private static string FindIndexedProcessName(int pid)
{
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;
for (var index = 0; index < processesByName.Length; index++)
{
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int)processId.NextValue() == pid)
{
return processIndexdName;
}
}
return processIndexdName;
}
private static Process FindPidFromIndexedProcessName(string indexedProcessName)
{
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
return Process.GetProcessById((int)parentId.NextValue());
}
public static Process Parent(this Process process)
{
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}
【讨论】: