简体   繁体   English

如何将选定的颜色从Form2发送到Form1

[英]How to send Selected color from form2 to form1

I have a Form1 with MenuItem 'Customize'. 我有一个带有MenuItem'Customize'的Form1。 On clicking customize, I open 'Form2'. 单击自定义后,我打开“ Form2”。 On Form2 , user selects two colors from ColorDialog. 在Form2上,用户从ColorDialog中选择两种颜色。 Form2 has 'Apply' button. Form2具有“应用”按钮。 I want on clicking 'Apply' button, Form2 should close(or Hide) and the chosen colors should be applied (painted) as backround color of Form1. 我想单击“应用”按钮,Form2应该关闭(或隐藏),并且所选的颜色应作为Form1的背景色应用(绘制)。 How do I do this? 我该怎么做呢?

您在form1中创建一个公共方法“ selectcolor()”,关闭所有窗体,打开一个新的form1并使用selectcolor()选择颜色

When you click the button to open form 2 do it like this: 当您单击按钮以打开窗体2时,请执行以下操作:

 Form2 f = new Form2();
 f.ShowDialog();
 var returnedColor = f.SelectedColor;

This will interupt the code in form1 so you cannot make changes there, and you return the value from the form. 这将中断form1中的代码,因此您无法在其中进行更改,而是从表单返回值。

public class Form2{
  public string SelectedColor = "Test";
}

This should work. 这应该工作。

In form 2 you need to have two properties that you can access to retrieve the colours 在表单2中,您需要具有两个属性,可以访问这些属性以检索颜色

public Color FirstColor {get; private set;}
public Color SecondColor {get; private set;}

Then to open this form you should use something along the following. 然后,要打开此表单,您应该使用以下内容。

using(var myForm = new Form2())
{
    myForm.ShowDialog();
    //if(myForm.ShowDialog() == DialogResult.OK)
        this.BackColor = myForm.FirstColor;
}

The commented line is an optional thing that you can introduce instead of the line above it if you have an ok/cancel button on your dialog. 如果对话框中有确定/取消按钮,则注释行是可选的,您可以引入而不是其上方的行。 To close the form you should set the forms DialogResult appropriately 要关闭表格,您应该适当设置表格DialogResult

you can use static variables like this: in Form1: 您可以使用如下静态变量:在Form1中:

Public Static Color SelectedColor;
Form1 f1 = new Form1();
f1.ShowDialog();
this.BackColor = SelectedColor;

in Form2: 在Form2中:

if(ColoeDialog1.ShowDialog()==DialogResault.OK)
{
Form1.SelectedColor = ColoeDialog1.SelectedColor;
}

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

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