Как отобразить вывод/окно консоли в приложении forms?
застрять сразу, очень простой пример:
если я скомпилирую это с параметрами по умолчанию (используя csc в командной строке), как и ожидалось, он будет компилироваться в консольное приложение. Кроме того, потому что я импортировал System.Windows.Forms , Он также покажет окно сообщения.
теперь, если я использую опцию /target:winexe Я думаю, что это то же самое, что Windows Application из параметров проекта, как и ожидалось, я буду видеть только окно сообщения и не выводить консоль.
(In факт, в тот момент, когда он запускается из командной строки, я могу выдать следующую команду, прежде чем приложение даже завершится).
Итак, мой вопрос — я знаю, что вы можете иметь вывод «windows»/forms из консольного приложения, но есть ли в любом случае, чтобы показать консоль из приложения Windows?
9 ответов:
создать проект Windows Form.
Затем: Свойства Проекта — > Приложение — > Тип Вывода — > Консольное Приложение
тогда может иметь консоль и формы, работающие вместе, работает для меня
Если вы не беспокоитесь об открытии консоли по команде, вы можете перейти в свойства для вашего проекта и изменить его на консольное приложение
Это будет по-прежнему показывать вашу форму, а также выскакивает окно консоли. Вы не можете закрыть окно консоли, но он работает как отличный временный регистратор для отладки.
просто не забудьте выключить его перед развертыванием программы.
можно назвать AttachConsole использование pinvoke для подключения окна консоли к проекту WinForms:http://www.csharp411.com/console-output-from-winforms-application/
вы также можете рассмотреть Log4net ( http://logging.apache.org/log4net/index.html) для настройки вывода журнала в различных конфигурациях.
это сработало для меня, чтобы передать вывод в файл. Вызовите консоль с помощью
cmd /c «C:\path\to\your\application.exe » > myfile.txt
добавьте этот код в приложение.
есть в основном две вещи, которые могут произойти здесь.
вывод на консоль Программа winforms может присоединяться к создавшему ее консольному окну (или к другому консольному окну, или даже к новому консольному окну, если это необходимо). После подключения к консоли окна консоли.WriteLine () etc работает так, как ожидалось. Один из них заключается в том, что программа немедленно возвращает управление в окно консоли, а затем продолжает писать в него, поэтому пользователь может также введите в окне консоли. Вы можете использовать start с параметром /wait, чтобы справиться с этим, я думаю.
перенаправление вывода консоли Это когда кто-то передает вывод из вашей программы куда-то еще, например.
прикрепление к окну консоли в этом случае эффективно игнорирует трубопроводы. Чтобы сделать эту работу вы можете вызвать консоль.OpenStandardOutput() для получения дескриптора поток, в который должен передаваться вывод. Это работает только в том случае, если вывод передается по конвейеру, поэтому, если вы хотите обработать оба сценария, вам нужно открыть стандартный вывод и записать его и прикрепить к окну консоли. Это означает, что вывод отправляется в окно консоли и в трубу, но это лучшее решение, которое я мог найти. Ниже код, который я использую для этого.
Вызов консоли в WinForm приложении
Как переделать с консоли на WinForm?
Первое слово в строке перевести в верхний регистр(большие буквы), как это реализовать в WinForm .
Вызов форм из консоли
Здравствуйте, уже неделю пытаюсь решить задачу, но пока результатов мало.. Задание: вызвать из.
Вызов консоли с winforms
мне нужно ввести несколько параметров с консоли в проекте winforms, но после первого ввода выдает.
Вызов из консоли системы
Добрый день всем. Скажу сразу — я любитель. C# — мое хобби что ли. Вопрос: Есть форма.
конечно реально. Какую именно консоль?
если просто консольное приложение надо:
Обычную консоль, как в консольном приложении.
Например ,что-бы считать данные можно было так :
как вызвать я написал, а как обеспечить синхронизацию ,сам придумай. Варианты есть разные.
Можешь через временный фаил.
Вот ещё почитай, хотя там тоже самое что я написал.
Запуск консольного приложения из WindowsForm
или ты как объект(класс объявить) хочешь в винформсе создать консль?
Именно это и хочу .
Идея в следующем :
Есть основная форма . В определенный момент она должна открыть консоль и считать оттуда введенные данные .
Решение
Решение
Спасибо огромное ,именно то что нужно было.
В Шилдте или Троелсене такого вроде нет.
И вопрос — когда создается консольное приложение то тоже импортируется эта библиотека?
где вы инфу по таким вещам берете? Имею в виду:
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Вызов winform из unity
Как из юнити приложения вызвать винформ? просто подключить using System.Windows.Forms; а затем.
Вывод консоли в оконном приложении
Мне нужно затестировать как работает функция, т.е. выводить каждую операцию. Что — то.
Вызов функции в .NET-приложении
Нужно решить не особо сложную задачу из умножения матриц. Решил использовать для этой цели matlab.
Вызов действия в стороннем приложении
можно ли как-то вызвать действие чтобы файл его выполил?
Console output in Windows Form
I’m building C# Windows Form application to search a specific directory. Output of the paths searched are sent to a console. How can I direct that method into a Windows’ form?
3 Answers 3
The simplest approach is to add a TextBox control to your form and set it to be multiline. Then each line of output is just appended to the control like this.
. if you prefer each line to be inserted at the top, making it easier to see the output without have to constantly scroll to the bottom of the TextBox then do this instead.
Thanks Phil. Problem I see now, I am storing the whole list of paths into a variable. The output is a block of paths. I like to have each path going to ‘textBox1’ dynamically changing, where every time a path is read, ‘textBox1’ displays it. Here is what I have:
I am not sure if I understand your requirements correctly. You can try this and tell us if this or something similar is what you are searching:
(just quick and dirty hacked together as a starting point):
This uses a ListBox for the display of the path and the size and a TextBox for display of the total size.
The Invoke call is important, as it allows to access the GUI from a thread (and a Task is another thread). If you omit the Invoke call, you get a cross thread exception.
On Stackoverflow you find many informations about this issue (accessing GUI from background thread and many different (better) ways to handle this.
How do I show a console output/window in a forms application?
To get stuck in straight away, a very basic example:
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?
12 Answers 12
this one should work.
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
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.
You can call AttachConsole using pinvoke to get a console window attached to a WinForms project: http://www.csharp411.com/console-output-from-winforms-application/
You may also want to consider Log4net ( http://logging.apache.org/log4net/index.html ) for configuring log output in different configurations.
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.
I found this code here: http://www.csharp411.com/console-output-from-winforms-application/ I thought is was worthy to post it here as well.
Create a Windows Forms Application, and change the output type to Console.
It will result in both a console and the form to open.
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.
Input and Output Methods
There are two different approaches to console I/O, the choice of which depends on how much flexibility and control an application needs. The high-level approach enables simple character stream I/O, but it limits access to a console’s input and screen buffers. The low-level approach requires that developers write more code and choose among a greater range of functions, but it also gives an application more flexibility.
The low-level approach is not recommended for new and ongoing development. Applications needing functionality from the low-level console I/O functions are encouraged to use virtual terminal sequences and explore our documentation on both classic functions versus virtual terminal and the ecosystem roadmap.
An application can use the file I/O functions, ReadFile and WriteFile, and the console functions, ReadConsole and WriteConsole, for high-level I/O that provides indirect access to a console’s input and screen buffers. The high-level input functions filter and process the data in a console’s input buffer to return input as a stream of characters, discarding mouse and buffer-resizing input. Similarly, the high-level output functions write a stream of characters that are displayed at the current cursor location in a screen buffer. An application controls the way these functions work by setting a console’s I/O modes.
The low-level I/O functions provide direct access to a console’s input and screen buffers, enabling an application to access mouse and buffer-resizing input events and extended information for keyboard events. Low-level output functions enable an application to read from or write to a specified number of consecutive character cells in a screen buffer, or to read or write to rectangular blocks of character cells at a specified location in a screen buffer. A console’s input modes affect low-level input by enabling the application to determine whether mouse and buffer-resizing events are placed in the input buffer. A console’s output modes have no effect on low-level output.
The high-level and low-level I/O methods are not mutually exclusive, and an application can use any combination of these functions. Typically, however, an application uses one approach or the other exclusively and we recommend focusing on one particular paradigm for optimal results.
The ideal forward looking application will focus on the high-level methods and augment further needs with virtual terminal sequences through the high-level I/O methods when necessary avoiding the use of low-level I/O functions entirely.
The following topics describe the console modes and the high-level and low-level I/O functions.