简体   繁体   English

关闭由ShowDialog()打开的表单

[英]Closing a form that was opened by ShowDialog()

I have a winform application where I've written my own little color picker that will only display system colours. 我有一个winform应用程序,其中编写了自己的小颜色选择器,该选择器仅显示系统颜色。 It's basically a TableLayoutPanel with a bunch of smaller panels added to it, to which I just set the background color. 它基本上是一个TableLayoutPanel ,上面添加了一堆较小的面板,我只是在上面设置了背景色。

Pretty simple: 很简单:

在此处输入图片说明

Now I'm opening this form for with: 现在,我使用以下方法打开此表单:

using (frmColourWindow colourPicker = new frmColourWindow (Cursor.Position.X, Cursor.Position.Y, findingPriority))
{
    colourPicker.ShowDialog();
    if (!colourPicker.SelectedColor.IsEmpty)
    {
        pnlColor.BackColor = colourPicker._SelectedColor;
    }                    
}

and closing it with by setting the DialogResult when the user has clicked on one of the color panels. 并通过在用户单击其中一个颜色面板时设置DialogResult关闭它。

This all works pretty good, the only thing I can not manage to get right is by closing the form when it loses focus (Eg when the user clicks somewhere else or starts typing). 这一切都很好,我唯一无法解决的就是在失去焦点时关闭窗体(例如,当用户单击其他地方或开始键入时)。 I've had a look at the Deactivate , LostFocus , and Leave events. 我看过DeactivateLostFocusLeave事件。 Just can't seem to get those events to fire when I want them to. 我似乎无法让这些事件触发。 Maybe I'm missing something obvious? 也许我缺少明显的东西?

As I mentioned in the comments, when using the ShowDialog() you can only use the Dialog you have opened and thus it never looses focus, so event like Deactivate , LostFocus and Leave won't work. 正如我在评论中提到的那样,当使用ShowDialog() ,只能使用已打开的对话框,因此它永远不会失去焦点,因此像DeactivateLostFocusLeave这样的事件将不起作用。

You need to use the Show() command to use those event to close the opened Form. 您需要使用Show()命令来使用那些事件来关闭打开的Form。

As to addressing the issue you pointed out in the comments about assigning the color to the object. 关于解决该问题,您在注释中指出了有关为对象分配颜色的问题。 you can do the following: 您可以执行以下操作:

Declare a public Property 声明公共财产

Color SelectedColor {get; private set; }

In your color picker and change your using statement to this: 在颜色选择器中,将您的using语句更改为:

var colourPicker = new frmColourWindow (Cursor.Position.X, Cursor.Position.Y, findingPriority);
colourPicker.Closed += (o, args) => { pnlColor.BackColor = colourPicker.SelectedColor };
colourPicker.Show(); 

This is of course just one of many possible solutions for that. 当然,这仅仅是许多可能的解决方案之一。

您可以通过使用Show()方法显示表单,然后使用Form.Deactivate事件来实现此目的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM