Search code examples
c#toggleswitchbunifu

How to make TopMost toggle switch


Hello there I'm trying to make TopMost toggle switch here's the code: private void bunifuiOSSwitch1_OnValueChange(object sender, EventArgs e)

private void bunifuiOSSwitch1_OnValueChange(object sender, EventArgs e)
        {
            Main main = new Main();
            if(bunifuiOSSwitch1.Value == true)
            {
                main.TopMost = true;
            }
            else
            {
                main.TopMost = false;
            }
        }

At first it worked when toggled to true and worked when toggled to false but when I tried to retoggle it on it didn't worked after that I tried to change the code again but that didn't worked too... Now it doesn't even TopMost.


Solution

  • What you need to do is pass a reference to Main into your Settings form. One way to do this is when you call Show() or ShowDialog():

    // ... in Form Main ...
    private void button1_Click(object sender, EventArgs e)
    {
        Settings settings = new Settings();
        settings.Show(this); // pass in this instance of Main as the "owner" of settings
    }
    

    Then, over in Settings, you can cast the .Owner property back to the Main type and take action on it:

    // ... in Settings Form ...
    private void bunifuiOSSwitch1_OnValueChange(object sender, EventArgs e)
    {
        if (this.Owner!=null && this.Owner is Main)
        {
            Main main = (Main)this.Owner;
            main.TopMost = (bunifuiOSSwitch1.Value == true);
        }
    }