我试图用这段代码检测C#中打开的表单;
from unittest.mock import MagicMock
class NuclearManager():
def __init__(self, reactor):
print("manager creating the nuclear reactor")
self.reactor = reactor
def start(self):
print("manager starting the nuclear reactor")
self.reactor.start()
def test():
mock_reactor = MagicMock()
nuke = NuclearManager(mock_reactor)
nuke.start()
nuke.start()
# These two prints would actually be asserts of some sort
print(mock_reactor.mock_calls)
print(mock_reactor.start.call_count)
test()
但是我的表单有manager creating the nuclear reactor
manager starting the nuclear reactor
manager starting the nuclear reactor
[call.start(), call.start()]
2
,我的代码无效。
如果表单具有属性if ((Application.OpenForms["Form1"] as Form1) != null)
{
Application.OpenForms["Form1"].Close();
}
?
答案 0 :(得分:2)
您需要做的是获得应用程序级别获取表单可以执行以下操作。
FormCollection openforms = Application.OpenForms;
foreach (Form frms in openforms)
{
if (frms.Name=="frmsomething")
{
frms.close();
}
//What ever you want do with individual forms in frms object
}
答案 1 :(得分:0)
似乎问题是ShowInTaskBar = false
导致.NET忽略打开表单列表中的表单。但是,您可以按照this SO answer中描述的方式使用Windows API将表单设置为不显示在任务栏中。
答案 2 :(得分:0)
Form2 form
private void btn1_Click(object sender, EventArgs e)
{
form = new Form2();
form.Show();
}
private void btn2_Click(object sender, EventArgs e)
{
if(form != null && !form.IsDisposed){
form.Close();
}
}