| ■No99451 (あいす さん) に返信 > フラグをForm1以外でも変更し、
そのフラグを Form1 で管理しているのなら、 Form1.cs で internal あるいは public で公開すれば、 他のフォームからでも、Form1のインスタンスのメンバーとして変更できるようになります。
Form1 のインスタンスメンバーとしたいのではなく、 プロジェクト全体で単一的に使う物なら、Program.cs で public static にしておけば、 Program.何某〜〜 としてアクセスできます。 あるいはシングルトンクラスを用意するということも出来るでしょう。
アプリケーション設定、たとえば Properties.Settings.Default.MyFlag = "何某"; などを使っているのであれば、さらに話は簡単で、 PropertyChanged イベントがそのまま変更通知として使えるので 自分でイベントを自作する必要すらありません。
[STAThread] static void Main() { Properties.Settings.Default.PropertyChanged += (sender, e) => { System.Diagnostics.Debug.WriteLine("{0}:{1}", e.PropertyName, Properties.Settings.Default[e.PropertyName]); if (e.PropertyName == "MyFlag") { MessageBox.Show("MyFlagが変更された"); } }; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
> 変更したいファイルで TestClass testClass; を宣言し > testClass.TestFlag = true;にしてもlabelが変わらなかったので、、
kiku さんのサンプルで言うと、 public partial class Form1 : Form { private TestClass testClass; } という状態になっているので、Form1 以外からは操作できません。
(案1) アクセス修飾子を、private から internal に格上げする public partial class Form1 : Form { internal readonly TestClass testClass = new TestClass(); }
(案2) インスタンスそのものは公開せず、フラグ操作部だけを公開する public partial class Form1 : Form { private readonly TestClass testClass = new TestClass(); public void ChangeFlag(bool newValue) { testClass.TestFlag = newValue; } }
Form1 のインタンス メンバーを別フォームからアクセスしたい場合は、 Form1 から他フォームを開く際に、Form1 の this を他フォームに受け渡しておくのが 手っ取り早いでしょう。(たとえば Owner プロパティに渡すこともできます)。
あるいは、Application.OpenForms を通じて動的に取得するということもできます。 |