如何通过编码点击按钮?

我的程序中有两个按钮,我希望当我按下第一个按钮时,第二个按钮被自动点击(在第一个按钮的事件处理程序中,我想通过编码按下第二个按钮)。

private void button1_Click(object sender, EventArgs e) { passWord = pwd.Text; user = uName.Text; loginbackend obj = new loginbackend(); bool isValid = obj.IsValidateCredentials(user, passWord, domain); if (isValid) { loginbackend login = new loginbackend(); passWord = pwd.Text; login.SaveUserPass(passWord); HtmlDocument webDoc = this.webBrowser1.Document; HtmlElement username = webDoc.GetElementById("__login_name"); HtmlElement password = webDoc.GetElementById("__login_password"); username.SetAttribute("value", user); password.SetAttribute("value", passWord); HtmlElementCollection inputTags = webDoc.GetElementsByTagName("input"); foreach (HtmlElement hElement in inputTags) { string typeTag = hElement.GetAttribute("type"); string typeAttri = hElement.GetAttribute("value"); if (typeTag.Equals("submit") && typeAttri.Equals("Login")) { hElement.InvokeMember("click"); break; } } button3_Click(sender, e); label1.Visible = false ; label3.Visible = false; uName.Visible = false; pwd.Visible = false; button1.Visible = false; button2.Visible = true; } else { MessageBox.Show("Invalid Username or Password"); } } private void button3_Click(object sender, EventArgs e) { HtmlDocument webDoc1 = this.webBrowser1.Document; HtmlElementCollection aTags = webDoc1.GetElementsByTagName("a"); foreach (HtmlElement link in aTags) { if (link.InnerText.Equals("Show Assigned")) { link.InvokeMember("click"); break; } } } 

我认为你所描述的是你想要在单击按钮B时调用方法,但是当单击按钮A时也调用该方法。

 protected void ButtonA_Click(...) { DoWork(); } protected void ButtonB_Click(...) { // do some extra work here DoWork(); } private void DoWork() { // do the common work here } 

根据您在事件处理程序中的实现,您也可以从第一个按钮中调用第二个按钮的事件处理程序,但上述方法是“正确”的方法。

你可以调用这个方法。

  private void btnA_Click(object sender, EventArgs e) { doA(); } private void doA() { //A stuff } private void btnB_Click(object sender, EventArgs e) { doA(); doB(); } private void doB() { //B stuff } 

或者直接调用_Click方法;

  private void btnB_Click(object sender, EventArgs e) { btnA_Click(sender, e); doB(); } 

我想,你真的不关心是否点击了按钮,你只关心第二个按钮的代码是否被执行。 所以…只需称呼它:

 void button1_Click(...) { button2_Click(...); }