Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a userControl is in front of others in C#?

Tags:

c#

.net

winforms

How do you check whether a userControl is in front of others? Is there easy way to do that? I use bringToFront method when my user control was clicked, but now I need to determine if it is in front at the moment.

like image 278
kubusabadi Avatar asked Jul 21 '10 12:07

kubusabadi


1 Answers

If you just want to know which control is at the front of a parent collection, just do the following:

private bool IsControlAtFront(Control control)
{
    return control.Parent.Controls.GetChildIndex(control) == 0;
}

Notice that the Z-Index 0 is the top most control, the higher the number, the lower down the hierarchy it is.

Also, this code above will currently only work for a Control within an individual parent. It will also need to recursively check the parent is at z-index 0 as well.

This will work for any Control anywhere within the Form:

private bool IsControlAtFront(Control control)
{
    while (control.Parent != null)
    {
        if (control.Parent.Controls.GetChildIndex(control) == 0)
        {
            control = control.Parent;
            if (control.Parent == null)
            {
                return true;
            }
        }
        else
        {
            return false;
        }
    }
    return false;
}
like image 199
djdd87 Avatar answered Oct 29 '22 12:10

djdd87