سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top