3

I have a WPF window without Titlebar and border. So I want change windows background based on it is active or not.

I writed code below but I got message Cannot implicitly convert type 'System.Drawing.Brush' to 'System.Windows.Media.Brush'.

Can you help me how to do this? Thank you!

    // This function used for both "Actived" and "Deactived" event
    private void window_Activated(object sender, EventArgs e)
    {
        Background = (IsActive)? System.Drawing.SystemBrushes.ActiveCaption :
            System.Drawing.SystemBrushes.InactiveCaption;
    }

EDIT
Current my windows title bar have Lime color if it active, and gray if inactive, but other user may be diffrent. How can I get these color by code?

NoName
  • 7,940
  • 13
  • 56
  • 108

1 Answers1

3

Since you're using WPF, instead of using the System.Drawing.SystemBrushes class you should use the System.Windows.SystemColors class. The brushes from the System.Drawing namespace are not directly compatible with the System.Windows.Media namespace brushes.

Background = (IsActive)? System.Windows.SystemColors.ActiveCaptionBrush :
            System.Windows.SystemColors.InactiveCaptionBrush;

If you want to use this in your XAML, you can use

Background="{x:Static SystemColors.ActiveCaptionBrush}"

Edit based on updated question

If you want to get the theme colour in use, you'll have to use PInvoke. The native method is DwmGetColorizationColor. This will return an integer so you can then create a SolidColorBrush with that integer and assign it to your background.

[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern void DwmGetColorizationColor(out int pcrColorization, [MarshalAs(UnmanagedType.Bool)]out bool pfOpaqueBlend);

int col;
bool opac;
DwmGetColorizationColor(out col, out opac);

//convert the int to a colour
byte[] bytes = BitConverter.GetBytes(col);
Color color = Color.FromRgb(bytes[2], bytes[1], bytes[0]);

Background = new SolidColorBrush(color);

That should get your Lime green color.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • That worked. Thank you. The color I get is default active/inactive color. Current my windows title bar have Lime color if it active, and gray if inactive. How can I get these color? – NoName Apr 16 '13 at 16:55
  • 1
    @TuyenTk - I've updated the answer. It should get your lime green colour. Does the `InactiveCaptionBrush` in the first answer not get the correct gray colour? – keyboardP Apr 16 '13 at 17:25
  • What about `bool opac`. I don't get the exact same color as the window active frame color but close, slightly burned. – Paul-Sebastian Manole Jul 20 '13 at 10:38
  • @Paul-SebastianManole - This thread my help with the opacity aspect http://stackoverflow.com/questions/3560890/vista-7-how-to-get-glass-color – keyboardP Jul 23 '13 at 11:36
  • 1
    thansk mannnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn...it was really helpful. – Relativity Oct 14 '13 at 20:31