簡體   English   中英

如何在C#控制台應用程序中創建無模式對話框

[英]How to create a modeless dialog box within a C# console app

我想用下面的代碼創建一個無模式對話框 但是,表單創建后似乎沒有響應。 我猜想如果以此方式創建消息循環,可能會阻止該消息循環。 有人知道如何以正確的方式創建它嗎?

class Program
{
    static void Main(string[] args)
    {
        Form form = new Form();
        form.Show();
        Console.ReadLine();
    }
}

顯示模態和無模Windows窗體:

將表單顯示為無模式對話框調用Show方法:
下面的示例顯示如何以無模式格式顯示“關於”對話框。

// C#
//Display frmAbout as a modeless dialog
Form f= new Form();
f.Show();

將窗體顯示為模式對話框調用ShowDialog方法。
以下示例顯示如何模態顯示對話框。

// C#
//Display frmAbout as a modal dialog
Form frmAbout = new Form();
frmAbout.ShowDialog();

請參閱: 顯示模態和無模Windows窗體


請參閱以下控制台應用程序代碼:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

class Test
{
    [STAThread]
    static void Main()
    {
        var f = new Form();
        f.Text = "modeless ";
        f.Show();

        var f2 = new Form() { Text = "modal " };

        Application.Run(f2);
        Console.WriteLine("Bye");

    }
}

您可以使用另一個線程,但是必須等待該線程加入或中止它:
像這樣的工作示例代碼:

using System;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApplication2
{
    static class Test
    {
        [STAThread]
        static void Main()
        {
            var f = new Form { Text = "Modeless Windows Forms" };
            var t = new Thread(() => Application.Run(f));
            t.Start();

            // do some job here then press enter
            Console.WriteLine("Press Enter to Exit");
            var line = Console.ReadLine();
            Console.WriteLine(line);

            //say Hi
            if (t.IsAlive) f.Invoke((Action)(() => f.Text = "Hi"));

            if (!t.IsAlive) return;
            Console.WriteLine("Close The Window");
            // t.Abort();
            t.Join();
        }
    }
}

終於,我開始工作了。 為了解除阻塞我的主線程,我必須使用一個新線程並調用Applicatoin.Run為該表單創建一個消息泵。 現在,窗體和主線程都處於活動狀態。 謝謝大家

class Program
{

    public static void ThreadProc(object arg)
    {
        Form form = arg as Form;
        Application.Run(form);
    }

    [STAThread]
    static void Main(string[] args)
    {
        Form form = new Form() { Text = "test" };

        Thread t = new Thread(ThreadProc);
        t.Start(form);
        string line = Console.ReadLine();
        Console.WriteLine(line);

        form.Close();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM