在 Visual Studio 中打开后控制台应用程序立即关闭 [英] Console application closes immediately after opening in visual studio

查看:46
本文介绍了在 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 中打开后控制台应用程序立即关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆