Как вывести консоль в visual studio
When doing a console application in Java with Eclipse, I see the output being put in a text box in the IDE itself, instead of having a console popping up like in Visual Studio. This comes in handy, as even after the program has exited, I can still make good use of the text that was written in it, as it doesn't get erased until I run it again. Is it possible to achieve anything like that with Visual Studio? I know that instead of doing
but it is not quite the same thing, as you get a lot of "junk" in the Output window, as all the loaded symbols and such.
Even better, is it possible to have everything done in the IDE itself, when you run your application, instead of having the console running?
12 Answers 12
In the Tools -> Visual Studio Options Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window".
I've checked this checkbox but I still get a Console popup and nothing in the "Output" window (Debug, Test, Build. ) or the "Immediate Window".
@EvenLisle you need to change the application type to Windows Application as in stolsvik's answer. The option mentioned in this answer was on by default for me in any case.
What does "Redirect All Output Window Text to the Immediate Window" excactly mean? Use various contexts if you need to. I am confused by what is the "immediate window".
@TooTone The question clearly states for a "console application" and changing it to something else just for debugging purposes, where I cannot even Console.ReadKey() is just straight up ridiculous!
In the Visual Studio Options Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window". Then go to your project settings and change the type from "Console Application" to "Windows Application". At that point Visual Studio does not open up a console window anymore, and the output is redirected to the Output window in Visual Studio. However, you cannot do anything "creative", like requesting key or text input, or clearing the console - you'll get runtime exceptions.
I find this particularly clumsy. What, I wonder, is the rationale behind this in VS? It should be the ability of all modern day IDE's to have a panel within the IDE itself behave as the console for input and output. (scratches head)
The question clearly states for a "console application" and changing it to something else just for debugging purposes, where I cannot even Console.ReadKey() is just straight up ridiculous!
Not sure why but when I tried to revert the Output type of my application back from Windows Application to Console then the console window is no where to be seen when I run my application. I'm able to debug the application and Main entry point is also getting hit. I also reverted the option setting mentioned in this post but to no avail. I'm using VS 2017 community edition. I lost my console window (sobbing).
For what it's worth, in VS 15.8.7 the only way I could get the output to redirect for a console app was to change it to a Windows app, and leave the Redirect box UNCHECKED. If I check the box, it does not display the output.
Depending on what listeners you attach, trace output can go to the debug window, the console, a file, database, or all at once. The possibilities are literally endless, as implementing your own TraceListener is extremely simple.
Yes, but what I want to know is if it is possible to just do it, without having to implement it by myself.
@devoured The Trace class outputs just to the debug window by default. You only need to attach extra listeners (and there are several already written you can use) if you want to also see the output elsewhere.
I went to my Debug Options dialog and chose "Redirect all Output Window text to the Immediate Window" to make the Trace output go to the Immediate window so it doesn't get all mixed up with the debug crap.
It's time to check the latest release/s for Visual Studio, folks. The most suggested solution that did not work for some of you before might work now.
In Visual Studio 2017 (Release Version 15.4.2 and above), going to Tools > Options > Debugging > General > (Check Box) Redirect all Output Window text to Immediate Window has worked for me.
- To see the Immediate Window, make sure that you are in Debugging mode.
- There should now be 3 other debugging tools available at your disposal, namely, Call Stack, Breakpoints, and Command Window, as shown below:
Doublecheck that the project you're testing with was created as a "console application", not a "windows application". Your approach works with a windows application, but that's not what the OP specified.
You could create a wrapper application that you run instead of directly running your real app. The wrapper application can listen to stdout and redirect everything to Trace. Then change the run settings to launch your wrapper and pass in the path to the real app to run.
You could also have the wrapper auto-attach the debugger to the new process if a debugger is attached to the wrapper.
You can try VSConsole which allow you to integrate its console window inside VisualStudio as dock panel at bottom. To use this you have to
- Add VSCodeExtension to VisualStudio
- Add VSCode NugetPackage reference in your project.
- Add using Console = VSConsole.Console; as namespace reference in *.cs file
- change the Output type from Console Application to Windows Application to hide the main console window that pops up when you run your console application.
Then your application will use VSConsole.Console class insted of System.Console class.
I know this is just another answer, but I thought I'd write something down for the new Web Developers, who might get confused about the "Change to a Windows Application" part, because I think by default an MVC application in Visual Studio 2013 defaults to an Output Type of Class Library.
My Web Application by default is set as an output type of "Class Library." You don't have to change that. All I had to do was follow the suggestions of going to Tools > Options > Debugging > Redirect all Output Window text to the Immediate Window. I then used the System.Diagnostics.Trace suggestion by Joel Coehoorn above.
Instead, you can collect the output in a test result.
You can't supply input, but you can easily provide several tests with different command line arguments, each test collecting the output.
If your goal is debugging, this is a low effort way of offering a repeatable debugging scenario.
regarding System.Diagnostics.Debug producing a lot of "junk" in the Output window: You can turn that off by right clicking in the output window. E.g. there's an item "Module Load Messages" which you want to disable and an item "Program Output" which you want to keep.
You have three possibilities to do this, but it's not trivial. The main idea of all IDEs is that all of them are the parents of the child (debug) processes. In this case, it is possible to manipulate with standard input, output and error handler. So IDEs start child applications and redirect out into the internal output window. I know about one more possibility, but it will come in future
If you need output from Console.WriteLine, and the Redirect All Output Window Text to the Immediate Window does not function and you need to know the output of Tests from the Integrated Test Explorer, using NUnit.Framework our problem is already solved at VS 2017:
When we click on Blue Output, under Elapsed Time, at right, and it produces this:
Standard Output is our desired Output, produced by Console.WriteLine.
It functions for Console and for Windows Form Applications at VS 2017, but only for Output generated for Test Explorer at Debug or Run; anyway, this is my main need of Console.WriteLine output.
Подготовка к отладке консольного проекта аналогична подготовке к отладке проекта Windows, с некоторыми дополнительными соображениями, такими как установка аргументов командной строки и приостановка приложения для отладки. Дополнительные сведения см. в статье Подготовка к отладке. Приложения Windows Forms. Из-за схожести всех консольных приложений в этом разделе описываются следующие типы проектов:
консольное приложение С++ (Win32).
Задание аргументов командной строки
Может потребоваться задание аргументов командной строки для консольного приложения. Дополнительные сведения см. в статьях Параметры проектов для конфигураций отладки C++ и Параметры проекта для конфигурации отладки Visual Basic, или Параметры проекта для конфигурации отладки C++.
Запуск приложения
Некоторые консольные приложения после запуска выполняются до полного завершения, после чего сразу закрываются. Если это происходит быстро, то можно не успеть прервать выполнение приложения и выполнить отладку. Чтобы можно было выполнить отладку такого приложения, необходимо использовать один из следующих приемов для запуска приложения.
Установите точку останова в коде и запустите приложение.
Запустите приложение, нажав клавишу F10 (Отладка > Шаг с обходом) или F11 (Отладка > Шаг с заходом), а затем пройдите по коду, используя другие параметры, такие как Run to click (Выполнение до щелчка).
В редакторе кода щелкните правой кнопкой мыши строку и выберите пункт Выполнить до текущей позиции.
При отладке консольного приложения может потребоваться запуск приложения из командной строки, а не из Visual Studio. В этом случае можно запустить приложение из командной строки и присоединить к нему отладчик Visual Studio. См. сведения о присоединении к выполняемым процессам.
При запуске консольного приложения из Visual Studio окно Консоль иногда отображается позади окна Visual Studio. Если при попытке запустить консольное приложение из Visual Studio кажется, что ничего не происходит, попробуйте переместить окно Visual Studio.
Visual Studio включает две оболочки командной строки для разработчиков, командную строку и экземпляр PowerShell, как показано ниже.
Командная строка разработчика для Visual Studio — стандартная командная строка с определенными переменными среды, упрощающая работу с инструментами разработки. Доступно с версии Visual Studio 2015.
PowerShell для разработчиков Visual Studio — более функциональное средство, чем командная строка. Например, в нем можно передать результат одной команды (называемой cmdlet ) в другой cmdlet. В этой оболочке доступны те же переменные среды, что и в Командной строке разработчика. Доступно с версии Visual Studio 2019.
Начиная с версии 16.5, в Visual Studio 2019 доступен встроенный терминал, где можно работать как с Командной строкой разработчика, так и с PowerShell для разработчиков. Можно открыть несколько вкладок для каждой оболочки. Терминал Visual Studio построен на основе Терминала Windows. Чтобы открыть терминал в Visual Studio, выберите элементы Вид > Терминал.
При запуске в Visual Studio одной из оболочек как отдельного приложения или в окне терминала открывается каталог текущего решения (если оно загружено). Это упрощает выполнение команд для решения или его проектов.
В обеих оболочках заданы определенные переменные среды. Это упрощает работу с инструментами командной строки. Открыв эти оболочки, можно выполнять команды для различных служебных программ, не указывая их расположения.
Запуск в Visual Studio
Выполните следующие действия, чтобы открыть в Visual Studio Командную строку разработчика или PowerShell для разработчиков:
Запустите Visual Studio.
В строке меню выберите элементы Инструменты > Командная строка > Командная строка разработчика или PowerShell для разработчиков.
Запуск из меню Windows
Другой способ запуска оболочек — из меню "Пуск". В зависимости от версии Visual Studio, дополнительно установленных пакетов SDK и рабочих нагрузок может иметься несколько вариантов командных строк.
Windows 11
Выберите для приложения результат, связанный с текстом поиска.
Windows 10
Разверните папку Visual Studio 2019 или Visual Studio 2022.
Если вы используете Visual Studio 2019, выберите Командная строка разработчика для VS 2019 или PowerShell для разработчиков для VS 2019. Если используется Visual Studio 2022, выберите Командная строка разработчика для VS 2022 или PowerShell для разработчиков для VS 2022.
Кроме того, вы можете начать вводить имя оболочки в поле поиска на панели задач и выбрать нужный результат, так как в списке результатов начнут отображаться найденные совпадения.
Windows 8.1
Перейдите на экран Пуск, нажав клавишу с логотипом Windows на клавиатуре, например.
На начальном экране нажмите Ctrl+Tab, чтобы открыть список приложений, а затем нажмите V. Появится список, включающий все установленные командные строки Visual Studio.
Если вы используете Visual Studio 2019, выберите Командная строка разработчика для VS 2019 или PowerShell для разработчиков для VS 2019. Если используется Visual Studio 2022, выберите Командная строка разработчика для VS 2022 или PowerShell для разработчиков для VS 2022.
Windows 7
Выберите Пуск а затем разверните Все программы.
Выберите элементы Visual Studio 2019 > Инструменты Visual Studio > Командная строка разработчика для VS 2019 или PowerShell для разработчиков для VS 2019. (Если вы используете Visual Studio 2022, найдите те же элементы, которые содержат "2022" вместо "2019".)
Если установлены другие пакеты SDK, например, пакет SDK для Windows 10 или предыдущих версий, могут появиться дополнительные командные строки. Требуемая версия командной строки указана в документации по соответствующим инструментам.
Запуск из обозревателя файлов
Обычно ярлыки для установленных оболочек помещаются в папку меню "Пуск" для Visual Studio, например в %ProgramData%\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools. Но если поиск командной строки не дает ожидаемых результатов, попробуйте вручную найти нужные файлы на компьютере.
Командная строка разработчика
Выполните поиск файла командной строки (VsDevCmd.bat) или перейдите в папку "Инструменты" Visual Studio ( %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools — путь зависит от версии Visual Studio, выпуска и расположения установки).
Когда вы найдете файл командной строки, откройте его. Для этого введите следующую команду в стандартном окне командной строки:
Кроме того, вы можете ввести следующую команду в диалоговом окне Windows Выполнить:
Не забудьте изменить путь в соответствии с используемой версией Visual Studio.
PowerShell для разработчиков
Найдите файл скрипта PowerShell с именем Launch-VsDevShell.ps1 или перейдите в папку "Инструменты" Visual Studio ( %ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\Common7\Tools). Путь зависит от версии, выпуска и расположения установки Visual Studio. После этого выполните следующую команду в командной строке Windows PowerShell или PowerShell 6:
По умолчанию PowerShell для разработчиков запускается с конфигурацией для той версии Visual Studio, путь установки к которой указан в файле Launch-VsDevShell.ps1.
Чтобы выполнить cmdlet, нужно задать политику выполнения.
Скрипт Launch-VsDevShell.ps1 находит модуль PowerShell Microsoft.VisualStudio.DevShell.dll в каталоге установки Visual Studio, скачивает модуль и вызывает командлет Enter-VsDevShell cmdlet. Установленные ярлыки, как в меню "Пуск", будут загружать модуль и вызывать cmdlet напрямую. Использование Launch-VsDevShell.ps1 — это рекомендуемый способ инициализации PowerShell для разработчиков в интерактивном режиме или автоматизации сборки скрипта.
аргументов командной строки;
Можно использовать аргументы командной строки для любой из оболочек, «Командная строка разработчика» или «PowerShell для разработчика».
Целевая архитектура и архитектура узла
Для средств сборки (таких как компилятор C++), которые создают выходные данные, предназначенные для конкретных архитектур ЦП, оболочки разработки можно настроить с помощью определенного аргумента командной строки. Архитектуру двоичных файлов средства сборки также можно настроить с помощью аргументов командной строки. Это полезно, если архитектура компьютера сборки отличается от целевой архитектуры.
Начиная с Visual Studio 2022, для msbuild по умолчанию будет использоваться 64-разрядный двоичный файл msbuild.exe, независимо от архитектуры узла.
Shell | Аргумент |
---|---|
Командная строка разработчика | -arch= |
Командная строка разработчика | -host_arch= |
PowerShell для разработчиков | -Arch |
PowerShell для разработчиков | -HostArch |
Аргументы -Arch и -HostArch в PowerShell для разработчика доступны только начиная с версии Visual Studio 2022 с обновлением 17.1.
Ниже приведена таблица со списком поддерживаемых архитектур. В нем также указано, можно ли их использовать для аргументов целевой архитектуры или архитектуры узла.
Архитектура | Целевая архитектура | Архитектура узла |
---|---|---|
x86 | По умолчанию | По умолчанию |
amd64 | Да | Да |
arm | Да | Нет |
arm64 | Да | Нет |
Если задана только целевая архитектура, оболочки будут пытаться сопоставить с ней архитектуру узла. Поэтому, если настроена только целевая архитектура со значением, не поддерживаемым для архитектуры узла, могут возникнуть ошибки.
Примеры
Запустите Командную строку разработчика для Visual Studio 2019 Community Edition на 64-разрядном компьютере, создав выходные данные сборки, предназначенные для 64-разрядной архитектуры:
Запустите Командную строку разработчика для Visual Studio 2019 Community Edition на 64-разрядном компьютере, создав выходные данные сборки, предназначенные для ARM:
Запустите PowerShell для разработчиков для версии Community Edition Visual Studio 2022 17.1 или более поздней версии на 64-разрядном компьютере, создав выходные данные сборки, предназначенные для arm64:
SkipAutomaticLocation
Начальный каталог оболочки PowerShell для разработчика — это расположение проекта Visual Studio. Этот язык по умолчанию переопределяет все остальные пути, например к рабочему каталогу. Такое поведение можно отключить с помощью аргумента командной строки -SkipAutomaticLocation . Это полезно, если, например, вы хотите, чтобы в оболочке использовался текущий каталог после инициализации.
Расположение проекта можно настроить в меню Средства > Параметры > Проекты &и решения > Расположение проекта.
Аргументы командной строки -Arch , -HostArch и -SkipAutomaticLocation поддерживаются скриптом Launch-VsDevShell.ps1 и командлетом Enter-VsDevShell cmdlet.
Как открыть терминал для выполнения команд оболочки в Visual Studio (версия сообщества)?
Вы можете иметь встроенный терминал внутри Visual Studio, используя одно из этих расширений:
Whack Whack Terminal
Терминал: cmd или powershell
Клавиши быстрого доступа: Ctrl \ , Ctrl \
Поддерживает: Visual Studio 2017
BuiltinCmd
Терминал: cmd или powershell
Ярлык: Ctrl Shift T
Поддерживает: Visual Studio 2013, 2015, 2017, 2019.
Обновление Visual Studio 2019:
Теперь vs имеет встроенный терминал
Чтобы изменить терминал по умолчанию
Инструменты> Параметры — Терминал> По умолчанию
До Visual Studio 2019
Из комментариев лучший ответ от @Hans Passant
Инструменты> Внешние инструменты> Добавить
Название: Терминал (или назовите его сами)
Команда = cmd.exe или Команда = powershell.exe
Инструменты> Терминал (или что вы указали в заголовке)
В качестве хитрого решения вы можете использовать консоль диспетчера пакетов. для выполнения cmd или PowerShell.
Ярлык для консоли диспетчера пакетов Alt T N O
Протестировано в версии сообщества Visual Studio 2017
Ярлык Ctrl + ` такой же, как код Visual Studio
Новым в самой последней версии Visual Studio является View -> Terminal, который открывает экземпляр Powershell как закрепляемое окно VS, а не плавающий экземпляр Powershell или cmd из командной строки разработчика.
Microsoft только что включила интегрированный терминал Windows в Visual Studio версии 16.3 Preview 3. Перейдите в Инструменты> Параметры> Функции предварительного просмотра, включите опцию Experimental VS Terminal и перезапустите Visual Studio.
В Visual Studio 2019 вы можете открыть окно команды / PowerShell из Tools > Command Line >
Не уверен, что это поможет, но обычно я вызываю командную строку, перейдя на вкладку «Синхронизация» в Team Explorer и нажав «Действия».
Когда открывается командная строка, она находится в каталоге проекта.
В Visual Studio 2019 — Инструменты> Командная строка> Командная строка разработчика. введите описание изображения здесь
Щелкните правой кнопкой мыши свое решение, и свойства выше — это опция открытой командной строки, которая дает доступ к командной строке по умолчанию cmd, powershell и разработчику, в качестве альтернативы вы можете использовать ярлыки Alt + Space для Default (cmd), Shift + Alt + , для Dev (cmd), Shift + Alt + . для Powershell
Visual studio как открыть консоль?
Вы можете открыть терминал, используя Ctrl + `, из представления | Переключить меню Integrated Terminal или в команду View> Toggle Integrated Terminal в палитре команд. Использование CMD+Shift+C или CTRL+Shift+C , но это будет только открыть новый вне редактора стандартной консоли Баша.
Как открыть консоль в Visual Studio 2019?
Поиск командной строки на компьютере
Как открыть терминал в Visual Studio?
Включение нового терминала в Visual Studio
Для этого перейдите в Tools > Options > Preview Features, поставьте галочку возле Experimental VS Terminal и перезапустите Visual Studio. После включения вы сможете вызвать его через View > Terminal Window или через поиск.
Как задать параметры командной строки в Visual Studio?
Чтобы передать аргументы командной строки в Visual Studio нужно:
- Выбрать в верхнем меню панель Проект;
- В появившейся вкладке выбрать Свойства;
- В открывшемся окне выбрать Отладка
- В правой части задать аргументы в поле Аргументы команды
Как запустить JS в Visual Studio Code?
В Visual Studio в VSCode нет немедленного окна, в отличие от Visual Studio. Но вы все равно можете выполнить Javascript в VSCode. Откройте файл JavaScript в VSCode, затем используйте ярлык Ctrl + Alt + N , код будет запущен, и вывод будет отображаться в окне вывода.
Как убрать открыть в Visual Studio?
Как открыть проект в Visual Studio Code?
Чтобы открыть проект в Visual Studio Code, выберите пункт Open Folder (Открыть папку) в меню File (Файл), перейдите в папку PartyInvites и щелкните на кнопке Select Folder (Выбрать папку).
Как запустить программу в Visual Studio Code Python?
Существует гораздо более простой способ запуска Python, без какой-либо конфигурации:
- Установите Расширение прогона кода
- Откройте файл кода Python в текстовом редакторе, затем используйте ярлык Ctrl+Alt+N или нажмите F1 , а затем выберите/введите Run Code , код будет запущен, и вывод будет отображаться в окне вывода.
Как открыть проект в Visual Studio 2017?
Открытие проекта из репозитория GitHub
Как запустить программу в Visual Studio 2019?
Чтобы запустить программу в Visual Studio, нажмите комбинацию Ctrl+F5 .
Как открыть Command Prompt?
Еще один способ быстро запустить командную строку «напрямую» — нажать клавиши Windows+R на клавиатуре и ввести cmd.exe в окно «Выполнить». Затем просто нажмите Ок.
Как запустить командную строку?
Открыть командную строку из строки поиска
Как обновить MS Visual Studio?
Обновление с помощью установщика Visual StudioUpdate by using the Visual Studio Installer
Как открыть консоль в Visual Studio?
Как получить доступ к консоли в Visual Studio?
обычно вы можете нажать CTRL-ALT-O, чтобы сделать его видимым. Или через меню с помощью View-> Output. Вы можете запустить свою программу: Отладка -> Начать без отладки. Консоль останется открытой после завершения программы.
Как открыть окно консоли в Visual Studio 2019?
Как открыть консоль в Visual Studio 2017?
Чтобы открыть терминал: используйте сочетание клавиш Ctrl `с обратным апострофом. Эта команда работает как для Linux, так и для macOS. Используйте команду меню View> Terminal.
Есть ли в Visual Studio консоль?
Как открыть консоль в Chrome?
Чтобы открыть консоль разработчика в Google Chrome, откройте меню Chrome в правом верхнем углу окна браузера и выберите Дополнительные инструменты> Инструменты разработчика. Вы также можете использовать сочетание клавиш Option + ⌘ + J (в macOS) или Shift + CTRL + J (в Windows / Linux).
Куда идет консоль WriteLine Visual Studio?
Он переходит в консоль (стандартный вывод) или в поток, на который настроена консоль. Окна вывода будут видны только в режиме отладки, и они будут отображать все, например. Приставка. WriteLine ("Debug MyVariable:" + MyVariable), когда вы доберетесь до них.
Как сделать так, чтобы мое консольное приложение оставалось открытым?
нажмите ctrl + f5, чтобы запустить приложение. Обязательно используйте консоль. ReadLine (); чтобы сохранить предыдущую консоль.
Как вы держите консоль в C ++?
Почему окно консоли сразу закрывается Visual Studio?
Автоматически закрывать консоль при остановке отладки:
Если вы запускаете без отладки (Ctrl + F5), то по умолчанию вам будет предложено нажать клавишу возврата, чтобы закрыть окно. Если вы хотите использовать отладчик, вы должны поставить точку останова на последней строке.
Как открыть командную строку?
Как скомпилировать в Visual Studio?
Как скомпилировать программу на C ++ в Visual Studio
Как мне попасть в консоль диспетчера пакетов?
Откройте консоль в Visual Studio с помощью команды Инструменты> Диспетчер пакетов NuGet> Консоль диспетчера пакетов. Консоль представляет собой окно Visual Studio, которое можно расположить и расположить по своему усмотрению (см. Раздел Настройка макетов окон в Visual Studio).
Что такое консоль в Visual Studio?
Как отобразить вывод в Visual Studio?
If I compile this with default options (using csc at command line), as expected, it will compile to a console application. Also, because I imported System.Windows.Forms , it will also show a message box.
Now, if I use the option /target:winexe , which I think is the same as choosing Windows Application from within project options, as expected I will only see the Message Box and no console output.
(In fact, the moment it is launched from command line, I can issue the next command before the application has even completed).
So, my question is - I know that you can have "windows"/forms output from a console application, but is there anyway to show the console from a Windows application?
@Doggett, simple - I am learning and want to understand why/how to do it, even if I never end up using it in a real application. At the moment, I am thinking of an option that gives extra commands/output such as in VLC, however TBH, I do not need it - again, just learning and want to understand it!
13 Answers 13
this one should work.
Awesome, this question seems to have been asked a lot, this is the only actual answer to the question I've been able to find, +1
I tested on Windows 8 and Windows 10: - AttachConsole works from a cmd box - AllocConsole works from Visual Studio. When alloc is needed, AttachConsole returns false. You should also call FreeConsole() before terminating the application in console mode. In my program I used Matthew Strawbridge's code (see below), with the AttachConsole() line modified to: if (!AttachConsole(-1)) AllocConsole();
This is not great, when run from the command line it pops open a separate console window, and when running from the command line and trying to use > to redirect the output I get a separate console window and zero output in my file.
Perhaps this is over-simplistic.
Create a Windows Form project.
Then: Project Properties -> Application -> Output Type -> Console Application
Then can have Console and Forms running together, works for me
While, yes, technically this can be used to allow what the poster is asking for - it is not a great solution. By doing this, if you then start your winforms application with the GUI - you will also get a console window opened. In this case, you would need something more like Mike de Klerk's answer.
This is the only solution where I have been able to get my Winforms app to write output to the console when run from the command line, or to write to file when redirected on command line with > . However, I was hoping for a solution that that would explain how to run as a "Console Application" only some of the time (i.e. to programmatically enable whatever it is that changing this mysterious Visual Studio setting does). Does anyone know how this works under the hood?
If you are not worrying about opening a console on-command, you can go into the properties for your project and change it to Console Application
This will still show your form as well as popping up a console window. You can't close the console window, but it works as an excellent temporary logger for debugging.
Just remember to turn it back off before you deploy the program.
Nice. This resolves the problem I have with my forms application, that I need to be able to output to a console window while supporting redirecting the output to a file. And I dont need to attach any console manually.
@JasonHarrison If you close the console window, the program closes. Also the window is always open while the program runs.
@gun2171: Thanks. The downsides to this approach is noted in the answer: the console window will appear if the application is launched with double click, Start menu, etc.
+1 - Wow, I was hoping for a console.show or similar! a lot more complicated than I thought! I will leave open for the moment just in case there is a better / easier answer.
This worked for me, AllocConsole() did not because it spawned a new console window (did not dig further into AllocConsole, maybe I missed something there though).
Create a Windows Forms Application, and change the output type to Console.
It will result in both a console and the form to open.
I have tried many examples, but none of them produced results that fulfilled my expectations. This solution however is exactly what I wanted and by far the easiest solution.
This worked for me, to pipe the output to a file. Call the console with
cmd /c "C:\path\to\your\application.exe" > myfile.txt
Add this code to your application.
This works great EXCEPT it now fails in Windows 8 and Windows 10. By fails I mean there's no output except and extra prompt (if that's a clue).Someone suggested AllocConsole but that just flashed a cmd window.
Also tried Chaz's answer above but that gives a new console in Windows 7 (lathough not in 8 or 10). I just need the option to run with redirection on the command line or run as a gui if there are no args.
I tried this but did not work. With just AttachConsole(ATTACH_PARENT_PROCESS) I get the console output but redirecting it on the command line with > does not work. When I try this answer, I can't get any output whatsoever, either in the console or in a file.
There are basically two things that can happen here.
Console output It is possible for a winforms program to attach itself to the console window that created it (or to a different console window, or indeed to a new console window if desired). Once attached to the console window Console.WriteLine() etc works as expected. One gotcha to this approach is that the program returns control to the console window immediately, and then carries on writing to it, so the user can also type away in the console window. You can use start with the /wait parameter to handle this I think.
Redirected console output This is when someone pipes the output from your program somewhere else, eg.
Attaching to a console window in this case effectively ignores the piping. To make this work you can call Console.OpenStandardOutput() to get a handle to the stream that the output should be piped to. This only works if the output is piped, so if you want to handle both of the scenarios you need to open the standard output and write to it and attach to the console window. This does mean that the output is sent to the console window and to the pipe but its the best solution I could find. Below the code I use to do this.
Читайте также: