콘솔 응용 프로그램에서 winform을 실행하는 방법은 무엇입니까?
콘솔 애플리케이션에서 winform을 생성, 실행 및 제어하려면 어떻게합니까?
가장 쉬운 방법은 Windows Forms 프로젝트를 시작한 다음 출력 유형을 Console Application으로 변경하는 것입니다. 또는 System.Windows.Forms.dll에 대한 참조를 추가하고 코딩을 시작하십시오.
using System.Windows.Forms;
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form()); // or whatever
}
중요한 비트는이 [STAThread]
당신에 Main()
방법, 전체 COM 지원을 위해 필요합니다.
나는 최근에 이것을하고 싶었고 여기에 대한 답변에 만족하지 않는다는 것을 알았습니다.
Marc의 조언을 따르고 출력 유형을 Console Application으로 설정하면 두 가지 문제가 있습니다.
1) Explorer에서 응용 프로그램을 시작하면 Form 뒤에 프로그램이 종료 될 때까지 사라지지 않는 성가신 콘솔 창이 나타납니다. GUI (Application.Run)를 표시하기 전에 FreeConsole을 호출하여이 문제를 완화 할 수 있습니다. 여기서 짜증나는 것은 콘솔 창이 여전히 나타납니다. 그것은 즉시 사라지지만 그럼에도 불구하고 잠시 동안 거기에 있습니다.
2) 콘솔에서 실행하고 GUI를 표시하면 GUI가 종료 될 때까지 콘솔이 차단됩니다. 이는 콘솔 (cmd.exe)이 콘솔 앱을 동기식으로, Windows 앱을 비동기식으로 실행해야한다고 생각하기 때문입니다 ( "myprocess &"에 해당하는 Unix).
출력 유형을 Windows 응용 프로그램으로 남겨두고 AttachConsole을 올바르게 호출하면 콘솔에서 호출 할 때 두 번째 콘솔 창이 표시되지 않고 탐색기에서 호출 될 때 불필요한 콘솔이 표시되지 않습니다. AttachConsole을 호출하는 올바른 방법은 -1을 전달하는 것입니다. 이로 인해 프로세스가 부모 프로세스 (우리를 시작한 콘솔 창)의 콘솔에 연결됩니다.
그러나 여기에는 두 가지 다른 문제가 있습니다.
1) 콘솔은 백그라운드에서 Windows 앱을 시작하기 때문에 즉시 프롬프트를 표시하고 추가 입력을 허용합니다. 한편으로 이것은 좋은 소식입니다. 콘솔이 GUI 앱에서 차단되지는 않지만 콘솔에 출력을 덤프하고 GUI를 표시하지 않으려는 경우 프로그램의 출력이 프롬프트 뒤에 나오고 새 프롬프트가 없습니다. 완료되면 표시됩니다. "콘솔 앱"이 백그라운드에서 실행되고 사용자가 실행 중에 다른 명령을 자유롭게 실행할 수 있다는 점은 말할 것도없고 약간 혼란스러워 보입니다.
2) 스트림 리디렉션도 엉망이됩니다. 예를 들어 "myapp some parameters> somefile"이 리디렉션에 실패합니다. 스트림 리디렉션 문제는 표준 핸들을 수정하기 위해 상당한 양의 p / Invoke가 필요하지만 해결할 수 있습니다.
많은 시간의 사냥과 실험 끝에 나는 이것을 완벽하게 할 방법이 없다는 결론에 도달했습니다. 부작용없이 콘솔과 창 모두의 모든 이점을 얻을 수는 없습니다. 응용 프로그램의 목적에 가장 덜 성가신 부작용을 선택하는 것이 중요합니다.
제가 찾은 최고의 방법은 다음과 같습니다. 먼저 프로젝트 출력 유형을 "Windows Application"으로 설정 한 다음 P / Invoke AllocConsole을 사용하여 콘솔 창을 만듭니다.
internal static class NativeMethods
{
[DllImport("kernel32.dll")]
internal static extern Boolean AllocConsole();
}
static class Program
{
static void Main(string[] args) {
if (args.Length == 0) {
// run as windows app
Application.EnableVisualStyles();
Application.Run(new Form1());
} else {
// run as console app
NativeMethods.AllocConsole();
Console.WriteLine("Hello World");
Console.ReadLine();
}
}
}
매우 간단합니다.
Main-method에 다음 속성과 코드를 추가하십시오.
[STAThread]
void Main(string[] args])
{
Application.EnableVisualStyles();
//Do some stuff...
while(!Exit)
{
Application.DoEvents(); //Now if you call "form.Show()" your form won´t be frozen
//Do your stuff
}
}
이제 WinForms를 완전히 보여줄 수 있습니다. :)
VS2005 / VS2008에서 winform 프로젝트를 만든 다음 해당 속성을 명령 줄 응용 프로그램으로 변경할 수 있습니다. 그런 다음 명령 줄에서 시작할 수 있지만 여전히 winform이 열립니다.
You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application
This worked for my needs...
Task mytask = Task.Run(() =>
{
MyForm form = new MyForm();
form.ShowDialog();
});
This starts the from in a new thread and does not release the thread until the form is closed. Task
is in .Net 4 and later.
Its totally depends upon your choice, that how you are implementing.
a. Attached process , ex: input on form and print on console
b. Independent process, ex: start a timer, don't close even if console exit.
for a,
Application.Run(new Form1());
//or -------------
Form1 f = new Form1();
f.ShowDialog();
for b, Use thread, or task anything, How to open win form independently?
If you want to escape from Form Freeze and use editing (like text for a button) use this code
Form form = new Form();
Form.Button.Text = "randomText";
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.Run(form);
All the above answers are great help, but I thought to add some more tips for the absolute beginner.
So, you want to do something with Windows Forms, in a Console Application:
Add a reference to System.Windows.Forms.dll in your Console application project in Solution Explorer. (Right Click on Solution-name->add->Reference...)
Specify the name space in code: using System.Windows.Forms;
Declare the needed properties in your class for the controls you wish to add to the form.
e.g. int Left { get; set; } // need to specify the LEFT position of the button on the Form
And then add the following code snippet in Main()
:
static void Main(string[] args)
{
Application.EnableVisualStyles();
Form frm = new Form(); // create aForm object
Button btn = new Button()
{
Left = 120,
Width = 130,
Height = 30,
Top = 150,
Text = "Biju Joseph, Redmond, WA"
};
//… more code
frm.Controls.Add(btn); // add button to the Form
// …. add more code here as needed
frm.ShowDialog(); // a modal dialog
}
참고URL : https://stackoverflow.com/questions/277771/how-to-run-a-winform-from-console-application
'Nice programing' 카테고리의 다른 글
Visual Studio에서 다중 선택? (0) | 2020.11.26 |
---|---|
Firestore로 "객체 배열"을 업데이트하는 방법은 무엇입니까? (0) | 2020.11.26 |
2 개의 어셈블리에 유형이 있습니다. (0) | 2020.11.26 |
부트 스트랩 탭 내용에 테두리를 지정하는 방법 (0) | 2020.11.26 |
WHERE 절에서 SELECT 문을 사용하여 SQL DELETE 문을 작성하는 방법은 무엇입니까? (0) | 2020.11.26 |