- how to run a winform from console application?
- 10 Answers 10
- Как в консольный проект подключить System.Windiws.Forms
- How can I make a .NET Windows Forms application that only runs in the System Tray?
- 10 Answers 10
- Работа с формами
- Основы форм
- Практическое руководство. Фоновое выполнение операции How to: Run an Operation in the Background
- Пример Example
- Компиляция кода Compiling the Code
how to run a winform from console application?
How do I create, execute and control a winform from within a console application?
10 Answers 10
The easiest option is to start a windows forms project, then change the output-type to Console Application. Alternatively, just add a reference to System.Windows.Forms.dll, and start coding:
The important bit is the [STAThread] on your Main() method, required for full COM support.
Exe netcoreapp3.1 true true
notice the Microsoft.NET.Sdk.WindowsDesktop and the UseWPF>true and the UseWindowsForms>true – Shaybc Aug 4 ’20 at 2:38
I recently wanted to do this and found that I was not happy with any of the answers here.
If you follow Marc’s advice and set the output-type to Console Application there are two problems:
1) If you launch the application from Explorer, you get an annoying console window behind your Form which doesn’t go away until your program exits. We can mitigate this problem by calling FreeConsole prior to showing the GUI (Application.Run). The annoyance here is that the console window still appears. It immediately goes away, but is there for a moment none-the-less.
2) If you launch it from a console, and display a GUI, the console is blocked until the GUI exits. This is because the console (cmd.exe) thinks it should launch Console apps synchronously and Windows apps asynchronously (the unix equivalent of «myprocess &»).
If you leave the output-type as Windows Application, but correctly call AttachConsole, you don’t get a second console window when invoked from a console and you don’t get the unnecessary console when invoked from Explorer. The correct way to call AttachConsole is to pass -1 to it. This causes our process to attach to the console of our parent process (the console window that launched us).
However, this has two different problems:
1) Because the console launches Windows apps in the background, it immediately displays the prompt and allows further input. On the one hand this is good news, the console is not blocked on your GUI app, but in the case where you want to dump output to the console and never show the GUI, your program’s output comes after the prompt and no new prompt is displayed when you’re done. This looks a bit confusing, not to mention that your «console app» is running in the background and the user is free to execute other commands while it’s running.
2) Stream redirection gets messed up as well, e.g. «myapp some parameters > somefile» fails to redirect. The stream redirection problem requires a significant amount of p/Invoke to fixup the standard handles, but it is solvable.
After many hours of hunting and experimenting, I’ve come to the conclusion that there is no way to do this perfectly. You simply cannot get all the benefits of both console and window without any side effects. It’s a matter of picking which side effects are least annoying for your application’s purposes.
Как в консольный проект подключить System.Windiws.Forms
System.Collections.IEnumerable; как его подключить?
int badhands ;//: System.Collections.IEnumerable; badhands =new int .
Как подключить System.Reactive вместе с mscore.dll?
Вообщем проблема такая, есть код: public IObservable .
Как подключить справку в формате pdf в проект
Нужно, чтобы по нажатии на кнопку вызывалась справка, а она в формате pdf Как это организовать?
Подключить DirectShow в Windows Forms Application (Visual Studio 2008)
Доброго время суток. Помогите подключить DirectShow в Windows Forms Application (Visual Studio.
Спасибо всем. А не подскажите как убрать «черный екран смерти» что-бы видно было только формы при запуске, а то я по книге не совсем догнал..
Добавлено через 2 минуты
kirill29, а как сделать следующе на си шарп:
Спасибо всем. А не подскажите как убрать «черный екран смерти» что-бы видно было только формы при запуске, а то я по книге не совсем догнал..
Добавлено через 2 минуты
kirill29, а как сделать следующе на си шарп:
1);
System.Windows.Forms.Application.Run(new Form1());
2)
System.Collections.Stack stack;
stack=new System.Collections.Stack()
//stack.Peek
//stack.Push
//stack.Pop
System.Console.Write(«10 konstruktorov»);
Спасибо, с этим разобрался. Но у меня есть еще вопросы:
есть ли в си шарпе вектора как в си++, или хотябы заменители..
Добавлено через 5 минут
как узнать длину строки? Допустим есть строка String s = «dfsdfsdf»; как узнать ее длину? и как обратиться к и-ому символу этой строки?
Добавлено через 1 минуту
мне больше понравился стек произвольных пипов))
Добавлено через 1 минуту
List<> — а где он должен быть (пространство имен)
Добавлено через 6 минут
как переписать этот клас, что-бы он работал?
Создай тот и другой на 1000000 элементов и сравни производительность.
Добавлено через 39 секунд
Error 1 The type or namespace name ‘List’ could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\Администратор\Мои документы\Visual Studio 2008\Projects\Project1\Project1\CodeFile1.cs 14 13 Project1
Добавлено через 21 секунду
HIMen, где он должен быть? я его у себя не нашел..
Alligieri, а можно как-то создать лист с Н элементами, значение которых К ?? Не прогоняя лист в цыкле
Добавлено через 18 минут
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Не удается подключить System.Threading.Tasks
Здравствуйте! Подскажите как подключить System.Threading.Tasks. Не удается объявить.
подключить Java class в проект C#
Доброго дня всем! Подскажите пожалуйста, каким образом подключить несколько классов Java (есть и.
How can I make a .NET Windows Forms application that only runs in the System Tray?
What do I need to do to make a Windows Forms application to be able to run in the System Tray?
Not an application that can be minimized to the tray, but an application that will be only exist in the tray, with nothing more than
10 Answers 10
The code project article Creating a Tasktray Application gives a very simple explanation and example of creating an application that only ever exists in the System Tray.
Basically change the Application.Run(new Form1()); line in Program.cs to instead start up a class that inherits from ApplicationContext , and have the constructor for that class initialize a NotifyIcon
As mat1t says — you need to add a NotifyIcon to your application and then use something like the following code to set the tooltip and context menu:
This code shows the icon in the system tray only:
The following will be needed if you have a form (for whatever reason):
The right click to get the context menu is handled automatically, but if you want to do some action on a left click you’ll need to add a Click handler:
I’ve wrote a traybar app with .NET 1.1 and I didn’t need a form.
First of all, set the startup object of the project as a Sub Main , defined in a module.
Then create programmatically the components: the NotifyIcon and ContextMenu .
Be sure to include a MenuItem «Quit» or similar.
Bind the ContextMenu to the NotifyIcon .
Invoke Application.Run() .
In the event handler for the Quit MenuItem be sure to call set NotifyIcon.Visible = False , then Application.Exit() . Add what you need to the ContextMenu and handle properly 🙂
- Create a new Windows Application with the wizard.
- Delete Form1 from the code.
- Remove the code in Program.cs starting up the Form1 .
- Use the NotifyIcon class to create your system tray icon (assign an icon to it).
- Add a contextmenu to it.
- Or react to NotifyIcon ‘s mouseclick and differenciate between Right and Left click, setting your contextmenu and showing it for which ever button (right/left) was pressed.
- Application.Run() to keep the app running with Application.Exit() to quit. Or a bool bRunning = true; while(bRunning)
. Then set bRunning = false; to exit the app.
«System tray» application is just a regular win forms application, only difference is that it creates a icon in windows system tray area. In order to create sys.tray icon use NotifyIcon component , you can find it in Toolbox(Common controls), and modify it’s properties: Icon, tool tip. Also it enables you to handle mouse click and double click messages.
And One more thing , in order to achieve look and feels or standard tray app. add followinf lines on your main form show event:
As far as I’m aware you have to still write the application using a form, but have no controls on the form and never set it visible. Use the NotifyIcon (an MSDN sample of which can be found here) to write your application.
Here is how I did it with Visual Studio 2010, .NET 4
- Create a Windows Forms Application, set ‘Make single instance application’ in properties
- Add a ContextMenuStrip
- Add some entries to the context menu strip, double click on them to get the handlers, for example, ‘exit’ (double click) -> handler -> me.Close()
- Add a NotifyIcon, in the designer set contextMenuStrip to the one you just created, pick an icon (you can find some in the VisualStudio folder under ‘common7. ‘)
- Set properties for the form in the designer: FormBorderStyle:none, ShowIcon:false, ShowInTaskbar:false, Opacity:0%, WindowState:Minimized
- Add Me.Visible=false at the end of Form1_Load, this will hide the icon when using Ctrl + Tab
- Run and adjust as needed.
It is very friendly framework for Notification Area Application. it is enough to add NotificationIcon to base form and change auto-generated code to code below:
Работа с формами
Основы форм
Внешний вид приложения является нам преимущественно через формы. Формы являются основными строительными блоками. Они предоставляют контейнер для различных элементов управления. А механизм событий позволяет элементам формы отзываться на ввод пользователя, и, таким образом, взаимодействовать с пользователем.
При открытии проекта в Visual Studio в графическом редакторе мы можем увидеть визуальную часть формы — ту часть, которую мы видим после запуска приложения и куда мы переносим элементы с панели управления. Но на самом деле форма скрывает мощный функционал, состоящий из методов, свойств, событий и прочее. Рассмотрим основные свойства форм.
Если мы запустим приложение, то нам отобразится одна пустая форма. Однако даже такой простой проект с пустой формой имеет несколько компонентов:
Несмотря на то, что мы видим только форму, но стартовой точкой входа в графическое приложение является класс Program, расположенный в файле Program.cs:
Сначала программой запускается данный класс, затем с помощью выражения Application.Run(new Form1()) он запускает форму Form1. Если вдруг мы захотим изменить стартовую форму в приложении на какую-нибудь другую, то нам надо изменить в этом выражении Form1 на соответствующий класс формы.
Сама форма сложна по содержанию. Она делится на ряд компонентов. Так, в структуре проекта есть файл Form1.Designer.cs, который выглядит примерно так:
Здесь объявляется частичный класс формы Form1, которая имеет два метода: Dispose() , который выполняет роль деструктора объекта, и InitializeComponent() , который устанавливает начальные значения свойств формы.
При добавлении элементов управления, например, кнопок, их описание также добавляется в этот файл.
Но на практике мы редко будем сталкиваться с этим классом, так как они выполняет в основном дизайнерские функции — установка свойств объектов, установка переменных.
Еще один файл — Form1.resx — хранит ресурсы формы. Как правило, ресурсы используются для создания однообразных форм сразу для нескольких языковых культур.
И более важный файл — Form1.cs, который в структуре проекта называется просто Form1, содержит код или программную логику формы:
Практическое руководство. Фоновое выполнение операции How to: Run an Operation in the Background
Если какая-либо операция будет выполняться в течение долгого времени и при этом требуется не допустить задержек в работе пользовательского интерфейса, можно использовать класс BackgroundWorker для выполнения операции в другом потоке. If you have an operation that will take a long time to complete, and you do not want to cause delays in your user interface, you can use the BackgroundWorker class to run the operation on another thread.
В примере ниже показано, как запустить операцию, занимающую длительное время, в фоновом режиме. The following code example shows how to run a time-consuming operation in the background. В форме есть кнопки Пуск и Отмена. The form has Start and Cancel buttons. Кнопка Пуск служит для запуска асинхронной операции. Click the Start button to run an asynchronous operation. Кнопка Отмена служит для остановки асинхронной операции. Click the Cancel button to stop a running asynchronous operation. Результат каждой операции выводится в элементе MessageBox. The outcome of each operation is displayed in a MessageBox.
В Visual Studio предусмотрена расширенная поддержка данной задачи. There is extensive support for this task in Visual Studio.
Пример Example
Компиляция кода Compiling the Code
Для этого примера требуются: This example requires: