2

我想用下面的代码创建一个无模式对话框。但是,表单在创建后似乎没有响应。我想如果我以这种方式创建它,消息循环可能会被阻止。任何人都知道如何以正确的方式创建它?

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

2 回答 2

4

显示模态和非模态 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();
        }
    }
}
于 2016-07-24T07:51:03.317 回答
1

最后,我让它工作了。为了解除对主线程的阻塞,我必须使用一个新线程并调用 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();
    }
}
于 2016-07-24T14:43:02.023 回答