简体   繁体   中英

C# - How to trigger opacity event when form loses focus?

Purpose is to have the opacity event trigger when the form loses focus. The form has a setting for STAY ON TOP. The visual effect would be to click on a possibly overlapping window, and yet the form when not focused on would stay on top, but in the corner slightly transparent, keeping it within easy access, but providing visibility to the stuff underneath.

I 've googled and googled, and can't figure out how to get this event to properly fire when form loses focus, and then when form gains focus back to restore opacity to 100% or the level determined elsewhere.

Tips?

// under designer.cs

// 
// CollectionToolForm
// 
//other code....
this.LostFocus += new System.EventHandler(goTransparent);



//method
          private void goTransparent(object sender, EventArgs e)
          {
               if (transparentCheck.Checked == true)
               {
                    this.Opacity = 0.50;
               }
               else
               {
                    this.Opacity = 1;
               }

          }

It sounds as if you are looking for the Activated and Deactivate events.

Update

In response to the comment about LostFocus event, it could be of interest to clarify how it works. The LostFocus event of the Form is inherited from Control . It is raised when a controls loses focus; either because the form as such is being deactivated (focus moves to another application for instance), or because focus moves to another control within the same form.

If you hook up an event handler for the LostFocus event of a form that contains only at least one control that can receive focus, you will find that the LostFocus event of the form is raised immediately after the form is displayed . This is because focus moves from the form (which is a Control ) to the first focusable control on the form.

So, the form being active and the form being focused are two separate behaviours.

You tried doing it with mouse enter/leave events?

public Form1()
{   
    this.MouseEnter += new System.EventHandler(this.Form1_MouseEnter);
    this.MouseLeave += new System.EventHandler(this.Form1_MouseLeave);
}

private void Form1_MouseLeave(object sender, EventArgs e)
{
    this.Opacity = 0.5;
}

private void Form1_MouseEnter(object sender, EventArgs e)
{
    this.Opacity = 1;
}

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