teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

AutoApplicationContext を改善

2021/11/13 17:42

投稿

KOZ6.0
KOZ6.0

スコア2736

answer CHANGED
@@ -58,22 +58,19 @@
58
58
 
59
59
  class AutoApplicationContext : ApplicationContext
60
60
  {
61
- public AutoApplicationContext(Form form) : base(form)
61
+ public AutoApplicationContext(Form form) : base(form) { }
62
- {
63
- form.FormClosed += Form_FormClosed;
64
- }
65
62
 
66
- private void Form_FormClosed(object sender, FormClosedEventArgs e)
63
+ protected override void OnMainFormClosed(object sender, EventArgs e)
67
64
  {
68
65
  foreach (Form form in Application.OpenForms)
69
66
  {
70
67
  if (!form.InvokeRequired)
71
68
  {
72
69
  this.MainForm = form;
73
- form.FormClosed += Form_FormClosed;
74
- break;
70
+ return;
75
71
  }
76
72
  }
73
+ base.OnMainFormClosed(sender, e);
77
74
  }
78
75
  }
79
76
 

1

VB6 風にしてみた

2021/11/13 17:42

投稿

KOZ6.0
KOZ6.0

スコア2736

answer CHANGED
@@ -34,4 +34,62 @@
34
34
  this.Close();
35
35
  }
36
36
  }
37
+ ```
38
+ #追記
39
+
40
+ VB6 風に、フォームが残っていたらメインフォームを自動で切り替えるようにしてみました。
41
+ (VB.NET の「Windowsアプリケーションフレームワークプロパティ」の
42
+ 「シャットダウンモード」を「最後のフォームが閉じるとき」にしたときの動き)
43
+
44
+ ```C#
45
+ using System;
46
+ using System.Windows.Forms;
47
+
48
+ static class Program
49
+ {
50
+ [STAThread]
51
+ static void Main()
52
+ {
53
+ Application.EnableVisualStyles();
54
+ Application.SetCompatibleTextRenderingDefault(false);
55
+ Application.Run(new AutoApplicationContext(new Form1()));
56
+ }
57
+ }
58
+
59
+ class AutoApplicationContext : ApplicationContext
60
+ {
61
+ public AutoApplicationContext(Form form) : base(form)
62
+ {
63
+ form.FormClosed += Form_FormClosed;
64
+ }
65
+
66
+ private void Form_FormClosed(object sender, FormClosedEventArgs e)
67
+ {
68
+ foreach (Form form in Application.OpenForms)
69
+ {
70
+ if (!form.InvokeRequired)
71
+ {
72
+ this.MainForm = form;
73
+ form.FormClosed += Form_FormClosed;
74
+ break;
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ public partial class Form1 : Form
81
+ {
82
+ public Form1()
83
+ {
84
+ InitializeComponent();
85
+ }
86
+
87
+ private void button1_Click(object sender, EventArgs e)
88
+ {
89
+ var f = new Form1();
90
+ f.Show();
91
+ this.Close();
92
+ }
93
+ }
94
+
37
95
  ```