| ■No85891 (しろ さん) に返信
> 「cForm2 なのかな?) のボタンを PerformClick しないと。」ってどうしたらよいのか
> 意味が分からないのですが・・どうしないといけないんですか?
質問者さんがやっているのは、自フォームのボタンクリックのイベントハンドラで、再度自フォー
ムのボタンをクリックしているので、永久ループになっているのは分かりますか?
やらなければいけないのは、自フォームのボタンクリックのイベントハンドラで生成した別フォー
ムの中にあるボタンをクリックしなければならないということは分かりますか?
そうするためには別フォームの中にあるボタンに外部からアクセスできる必要があるのですが、
デザイナでツールボックスから Button を Form にドラッグ&ドロップするとその Button のアク
セス修飾子は private になって外部からはアクセスできません。
なので、例えば(あくまで例えばです)、外部から Button にアクセスできるようパブリックプロ
パティを定義して、それを通じでアクセスすれば望むことができると思います。
具体的には、Form2 というのを作ってそれに Button をドラッグ&ドロップしたとすると、以下
のようにパブリックプロパティを追加します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
// button1 にアクセスするためのパブリックプロパティ
public Button Button1
{
get { return this.button1; }
}
}
}
それを Form1 のボタンクリックで以下のように使います。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Security.Principal;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Button1.Click += Form2ButtonClick;
f.Show();
f.Button1.PerformClick();
}
private void Form2ButtonClick(object sender, EventArgs e)
{
MessageBox.Show("button clicked");
}
}
} |