C# 如何确定控制台应用程序是如何启动的?
我如何判断用户是否通过双击EXE(或快捷方式)启动了我的控制台应用程序,或者他们是否已经打开了一个命令行窗口并在该会话中执行了我的控制台应用程序?您可以通过调用Win32函数来判断C# 如何确定控制台应用程序是如何启动的?,c#,.net,command-line,console,console-application,C#,.net,Command Line,Console,Console Application,我如何判断用户是否通过双击EXE(或快捷方式)启动了我的控制台应用程序,或者他们是否已经打开了一个命令行窗口并在该会话中执行了我的控制台应用程序?您可以通过调用Win32函数来判断 [DllImport("kernel32", CharSet=CharSet.Auto)] internal static extern void GetStartupInfo([In, Out] STARTUPINFO lpStartupInfo); 将此静态字段粘贴到“程序”类中,以确保它在任何输出之前运行:
[DllImport("kernel32", CharSet=CharSet.Auto)]
internal static extern void GetStartupInfo([In, Out] STARTUPINFO lpStartupInfo);
将此静态字段粘贴到“
程序
”类中,以确保它在任何输出之前运行:
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;
这有点过分/偏执,但在从Explorer启动时,不会对cls&&app.exe
(通过检查完整路径)或甚至cls&&“f:\ull\path\to\app.exe”
(通过查看标题)做出响应
我是从学校里得到这个主意的 您可以了解父进程是什么:
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));
}
}
公共静态类扩展
{
私有静态字符串FindIndexedProcessName(int-pid)
{
var processName=Process.GetProcessById(pid).processName;
var processesByName=Process.GetProcessesByName(processName);
字符串processIndexdName=null;
for(var index=0;index
I添加了第二个字段的可能重复项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]。包含(“vshost”)代码>在从VS启动时也等待按键