Check out my new blog at https://shibumiware.blogspot.com

Tuesday, May 23, 2017

Some Handy Extension Methods

Here are three, all extension methods. The first changes the dirty gray color of a Multiple Document
Interface client area into what ever color you like. The second will invoke events by name on any
object.    The third shows or hides the bevel (3D-sink) of the MDIClient area:

Pretty MDI Client

public static class ControlExtensions
{
    public static void MdiClientSetBackgroundColor(this Form form, Color color)
    {
        MdiClient control = form.Controls.OfType<MdiClient>().FirstOrDefault();
 
        if (control == null)
        {
            return;
        }
 
        control.BackColor = color;
 
    }
 
    public static void Raise<TEventArgs>(this object source, string eventName, TEventArgs eventArgs)
    {
        EventInfo eventInfo = source.GetType().GetEvent(eventName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
 
        if (eventInfo == null)
        {
            return;
        }
 
        FieldInfo fieldInfo = source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic);
 
        if (fieldInfo == null)
        {
            return;
        }
 
        object eventDelegateObject = fieldInfo.GetValue(source);
 
        if (eventDelegateObject == null || eventDelegateObject.GetType() != typeof(MulticastDelegate))
        {
            return;
        }
 
        MulticastDelegate eventDelegate = (MulticastDelegate)eventDelegateObject;
 
        foreach (Delegate handler in eventDelegate.GetInvocationList())
        {
            if (handler?.Method != null) handler.Method.Invoke(handler.Targetnew[] { source, eventArgs });
        }
    }
}
public static bool SetBevel(this Form form, bool show)
{
    MdiClient control = form.Controls.OfType<MdiClient>().FirstOrDefault();
 
    if (control == null)
    {
        return false;
    }
 
    int windowLong = Native.GetWindowLong(control.HandleNative.GWL_EXSTYLE);
 
    if (show)
    {
        windowLong |= (int)Native.WindowStyleEx.WS_EX_CLIENTEDGE;
    }
    else
    {
        windowLong &= (int)~Native.WindowStyleEx.WS_EX_CLIENTEDGE;
    }
 
    Native.SetWindowLong(control.HandleNative.GWL_EXSTYLEwindowLong);
 
    Native.SetWindowPos(control.HandleIntPtr.Zero, 0, 0, 0, 0,
        (uint) (Native.SetWindowPosOptions.SWP_NOACTIVATE |
                Native.SetWindowPosOptions.SWP_NOMOVE |
                Native.SetWindowPosOptions.SWP_NOSIZE |
                Native.SetWindowPosOptions.SWP_NOZORDER |
                Native.SetWindowPosOptions.SWP_NOOWNERZORDER |
                Native.SetWindowPosOptions.SWP_FRAMECHANGED));
 
    return true;
}



No comments :

Disclaimer

Content on this site is provided "AS IS" with no warranties and confers no rights. Additionally, all content on this site is my own personal opinion and does not represent my employer's view in any way.