在没有应用程序的情况下处理表单事件
本文关键字:处理 表单 事件 情况下 应用程序 | 更新日期: 2023-09-27 18:27:26
我有一个windows窗体,但没有在应用程序中运行它。
这是我必须在表单中调用的核心函数…有一些类变量,唯一真正重要的是closingpermission。用户必须按下按钮来关闭窗口。
不幸的是,我无法让它更新和处理事件。this.Update()
、this.Refresh()
不会起作用。
internal short ask(String question, String RegExFilter, out String answer)
{
this.RegExFilter = RegExFilter;
this.Text = question;
this.Show();
while (!closingpermission)
{
//Window needs to process its events and allow the user to interact.
}
answer = answerBox.Text;
this.Close();
return RetVal;
}
编辑:
"应用程序"是指单例应用程序——我没有。
循环必须保持形式的显示——我认为soution是Hans Passant写的。我需要发送一个信息循环。
Ken2K的解决方案对我不起作用。
编辑#2:
这里有一个可编译的例子-更新方法刷新了我的窗口,但我不能编辑文本框-更不用说按钮或我接下来要对文本做什么了。我甚至无法编辑文本。
using System.Windows.Forms;
using System.Drawing; //System.Drawing.dll
namespace StackOverFlowDemo
{
class Example
{
public static void Main()
{
Input input = new Input();
input.Ask("Something");
}
}
class Input : Form
{
TextBox textbox = new TextBox();
public Input()
{
this.Controls.AddRange(new Control[] { textbox });
this.Bounds = new Rectangle(0, 0, 500, 500);
this.textbox.Bounds = new Rectangle(10, 10, 480, 200);
}
internal void Ask(string question)
{
this.Text = question;
this.Show();
while (true)
{
this.Update();
}
}
}
}
编辑#3
我想我想要的是做不到的。我读了这个话题,似乎你需要一个一直调用protected override void WndProc(ref Message m);
的"东西"。这似乎是应用程序。我不知道在没有应用程序的应用程序中有任何方法可以做到这一点。请不同意我的意见:)
据我所知,您正试图向用户弹出一个Form,并要求他输入一些文本。不要做无限循环,它不起作用。CCD_ 4和CCD_。
您可以使用模态形式(通常更适合于向用户提示值的弹出窗口)和FormClosingEventArgs
:的Cancel
属性
public partial class Form2 : Form
{
private bool preventClose = true;
public string ResultString
{
get
{
// Returns the content of a textbox
return this.textBox1.Text;
}
}
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Closes only when button1 is clicked
this.preventClose = false;
this.Close();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = this.preventClose;
}
}
using (Form2 frm = new Form2())
{
frm.ShowDialog();
string res = frm.ResultString;
}
简单的解决方案是使用Application.DoEvents();
,但我对您的标题有点困惑。
第一批评论者中的一位从一开始就有正确的答案。
显然它不起作用,因为你没有"应用程序"。这个Application.Run()调用是保持表单活动所必需的,它将消息循环。或者Form.ShowDialog()。–Hans Passant 3月9日12:34
如果你想使用Froms,你也必须使用应用程序——如果你不想使用应用程序,你必须切换到其他一些可视化框架,比如XNA。
接受您的应用程序中有一个singleton并使用该应用程序。