简体   繁体   中英

Change TopMost property on a DIFFERENT form?

So in my program I have a settings page. On the settings page, there is an option to set the program "Always on Top". When this option is checked and unchecked, it properly saves the setting, but it does not actually change TopMost property itself.

The program's main form is called "MainForm", but the settings page is called "SettingsForm". How would I change the "TopMost" property on "MainForm", from within the "SettingsForm"?

You could create an event on Settings form:

public event EventHandler TopMostEvent;

private void OnTopMostEvent()
{
    if (TopMostEvent != null)
    {
       TopMostEvent(this, EventArgs.Empty);
    }
}

On CheckedChanged event call the method after saving settings:

 OnTopMostEvent();

And in Main form subscribe to the event and set the forms TopMost property

One approach would be to simply give SettingForm a reference to MainForm , eg via a constructor parameter which is then stored to a field where it can later be accessed when necessary.

For example:

public class SettingsForm
{
    public SettingsForm(MainForm mainForm)
    {
        this.mainForm = mainForm;
    }

    public void Apple()
    {
        this.mainForm.TopMost = true;
    }

    private readonly MainForm mainForm;
}

public class MainForm
{
    public void Banana()
    {
        var settingsForm = new SettingsForm(this);
        settingsForm.ShowDialog();
    }
}

(However, it may not be necessary to do this if the owner of SettingsForm is already the insntance of MainForm but this I cannot tell from what you have given.)

This is a good place for a mediator pattern. (Similar to a controller) The idea is you have one object that creates all of your windows and passes a reference to itself into each form through the constructor. You can call a method in the mediator from either form and the mediator will focus the MainForm. It's a very common practice in Windows Forms.

So you'll make a mediator class like so:

public class MyMediator { Form mainForm {get;set;} Form settingsForm{get;set;}

  public MyMediator() { mainForm = new MainForm(this); mainForm.Show(); } ... public FocusMainForm() // call this from settings form { mainForm.TopMost = true; } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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