如何通过双击EXE(或快捷方式)来判断用户是否已启动我的控制台应用程序,或者是否已打开命令行窗口并在该会话中执行我的控制台应用程序?
答案 0 :(得分:8)
将此静态字段粘贴到“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得到了这个想法。
答案 1 :(得分:1)
您可以通过P /调用Win32 GetStartupInfo()函数来解决这个问题。
[DllImport("kernel32", CharSet=CharSet.Auto)]
internal static extern void GetStartupInfo([In, Out] STARTUPINFO lpStartupInfo);
答案 2 :(得分:0)
您可以了解父进程是什么:
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));
}
}