简体   繁体   English

如何在控制台应用程序中打开一个窗口?

[英]How to open a window in console application?

I need to display a window in an application, but it is console. 我需要在应用程序中显示一个窗口,但这是控制台。

I've tried using: 我试过使用:

Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

The code stayed like this. 代码保持这样。

static void Main(string[] args)
        {


            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);
            ConnectToServer();
            RequestLoop();   
             Application.EnableVisualStyles(); 
             Application.SetCompatibleTextRenderingDefault(false);
             Application.Run(new Form1());

        }

But the window does not open, if I put the code first the window opens, but the console does not execute the command. 但是窗口不会打开,如果我先放置代码,则会打开窗口,但是控制台不会执行命令。

static void Main(string[] args)
            {
                   Application.EnableVisualStyles(); 
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());

                _handler += new EventHandler(Handler);
                SetConsoleCtrlHandler(_handler, true);
                ConnectToServer();
                RequestLoop();                      

            }

Neither of the two codes works. 这两个代码都不起作用。

In the first code the window does not open. 在第一个代码中,窗口不会打开。

In second code the window is opened, but the console does not execute the commands 在第二个代码中,打开了窗口,但是控制台不执行命令

The problem is that you are running console and window in the same thread. 问题是您在同一线程中运行控制台和窗口。 When you launch your window, because the thread is the same as the console, the thread is processing the window and not concurrently the console. 当您启动窗口时,由于线程与控制台相同,因此线程正在处理窗口,而不是同时处理控制台。 To run the console and window concurrently (in separate threads): change 要同时运行控制台和窗口(在单独的线程中):

Application.Run(new Form1());

to

Task.Run(() => Application.Run(new Form1()));

This will set another thread for your Window and the console will still be processing. 这将为您的Window设置另一个线程,并且控制台仍在处理中。 在此处输入图片说明

Task.Run(() => Application.Run(new Form1()));

在此处输入图片说明

Try this, you are forgetting 'Console.ReadLine();', if it is not threre than your console app will be closed, and your window also. 尝试此操作,您会忘记“ Console.ReadLine();”,如果它不存在,那么您的控制台应用程序将被关闭,并且您的窗口也会被关闭。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(() => Application.Run(new Form1()));
            Console.ReadLine();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM