我正在学习如何使用Windows Forms。我有一个主窗口窗体(MainForm)控制一切。在执行期间的某个时刻,我想打开另一个包含Listbox(ListboxForm)和一个按钮(DoneButton)的Windows窗体,该窗口指示用户何时完成ListboxForm。我已经设法让ListboxForm出现,但我不确定如何让MainForm等待并在用户按下DoneButton后继续执行。
现在,当弹出ListboxForm并且用户单击DoneButton时,仍会显示ListboxForm并且没有任何反应。我不确定为什么会发生这种情况 - 我在DoneButton的按钮代码中有一个this.close。
这是我的ListboxForm代码:
Public Class SessionController
Public Sub New()
OnLoginAttempted(BranchLocation.Manhattan, "testUser")
End Sub
Public Overridable Sub OnLoginAttempted(ByVal branchLocation As BranchLocation, ByVal username As String)
Dim eventHub As New EventHub
Dim eventArgs As New LoginAttemptedEventArgs(branchLocation, username, password)
eventHub.Publish(Me, eventArgs)
End Sub
End Class
Public Class Subscriber
Public Sub New()
Dim eventHub As New EventHub
eventHub.Register(AddressOf TestMethod)
End Sub
Public Sub TestMethod(ByVal sender As Object, ByVal e As LoginAttemptedEventArgs)
MessageBox.Show("Success1")
End Sub
End Class
和MainForm打开/创建一个像这样的ListboxForm:
public partial class ListboxForm : Form
{
List<string> _items = new List<string>();
public UpdateGhubAndWebConfigForm()
{
InitializeComponent();
_items.Add("Option 1");
_items.Add("Option 2");
_items.Add("Option 3");
listBox1.DataSource = _items;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { }
// This is for 'DoneButton'
private void button1_Click(object sender, EventArgs e)
{
LoggingProvider.Log.Info("ListboxForm DoneButton clicked with index: " + listBox1.SelectedIndex.ToString());
DoStuff();
this.Close();
}
private void Form1_Load(object sender, EventArgs e) { }
private void label1_Click(object sender, EventArgs e) { }
public static void DoStuff() { }
}
答案 0 :(得分:1)
如果您想要收听表单的任何事件,您需要订阅该委托,基本上,您的MainForm会创建一个ListboxForm实例,该实例具有您要单击的Button。将按钮的可见性公开
public Button button1....
然后从您的方法订阅事件
if(displayListboxForm == true)
{
var listboxForm = new ListboxForm();
//subscribing to the click event
listboxForm.button1.Click += YourMethod;
listboxForm.ShowDialog();
// Now I want MainForm to wait until the user clicks DoneButton in ListboxForm
MessageBox.Show("User has selected an option from ListboxForm");
}
public void YourMethod(EventArgs e)
{
//your logic here when the button is clicked
}
希望这有帮助