控制台应用程序在 Visual Studio 中打开后立即关闭

时间:2023-03-25
本文介绍了控制台应用程序在 Visual Studio 中打开后立即关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试在用 C# 构建的 Visual Studio 中打开一个控制台应用程序.我一打开它就立即关闭.

I am trying to open a console application in visual studio built in C#. As soon as I open it, it closes immediately.

我知道 Windows 设置这是一个安全默认值(至少我认为).我该如何解决?

I know windows sets this is a a safety default (atleast I think). How do I fix this?

我知道我可以编译它并创建快捷方式并修改目标,使其在应用程序位置之前具有命令提示符的位置.虽然创建它的程序员让它生成信息到 Visual Studio 的输出中,所以我必须只在那里打开它.

I know I can compile it and create a shortcut and modify the target so it has the location of the command prompt in it before the applications location. Although the programmer who created this has it generating information into the output of visual studio, so it's imperative that I only open it there.

大多数应用程序都会发生这种情况,而不仅仅是在 Visual Studio 中,只是在这种情况下,我需要在 VS 2010 中打开它.我使用的是 Windows 7.

It happens with most applications and not just in visual studio, just in this case I need it to open in VS 2010. I am using Windows 7.

推荐答案

这是一个古老的问题,并启发了几部有趣的漫画:

This is an ancient problem and has inspired several funny cartoons:

让我们修复它.您要做的是在从桌面、Windows 资源管理器或 Visual Studio 上的快捷方式启动控制台应用程序时提示用户按 Any 键.但不是当它从运行自己的控制台的命令处理器启动时.您可以通过一点点 pinvoke 来执行此操作,您可以确定该进程是否是控制台窗口的唯一所有者,如下所示:

Let's fix it. What you want to do is prompt the user to press the Any key when the console app was started from a shortcut on the desktop, Windows Explorer or Visual Studio. But not when it was started from the command processor running its own console. You can do so with a little pinvoke, you can find out if the process is the sole owner of the console window, like this:

using System;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Working on it...");
        //...
        Console.WriteLine("Done");
        PressAnyKey();
    }

    private static void PressAnyKey() {
        if (GetConsoleProcessList(new int[2], 2) <= 1) {
            Console.Write("Press any key to continue");
            Console.ReadKey();
        }
    }

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern int GetConsoleProcessList(int[] buffer, int size);
}

这篇关于控制台应用程序在 Visual Studio 中打开后立即关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:从控制台 C# 上的位置读取 下一篇:如何在 C# 控制台应用程序中捕获 ctrl-c (SIGINT)

相关文章