简体   繁体   中英

Windows forms button background transparent

I have WPF app with ContentControl where the content is WindowsFormsHost with a Child having custom panel, which renders SDL stream. Now I have added button to disable/enable audio of the stream. Everything works fine, but I cannot make the button icon transparent. How can I do that? Is it possible at all?

在此处输入图像描述

AudioButton = new System.Windows.Forms.Button()
{
   Enabled = AudioButtonEnabled,
   BackColor = Color.Transparent,
   Image = Image.FromFile(@".\Images\audioDisabled.png"),
   Width = 30,
   Height = 30,
   FlatStyle = System.Windows.Forms.FlatStyle.Flat
};
AudioButton.FlatAppearance.BorderSize = 0;
AudioButton.Click += (object sender, EventArgs e) =>
{
   
};
SDLRenderer.AddButton(AudioButton);

The image (icon) is transparent as well.

The workaround can be to create custom WinForms button, override OnPaint event and make the specified color transparent for bitmap by calling Bitmap.MakeTransparent()

public class CustomButton : Button
{
    private Color TransparentColor;

    public CustomButton() : base()
    {
        TransparentColor = Color.FromArgb(192, 192, 192);
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        if (this.Image != null)
        {
            Bitmap bmp = ((Bitmap)this.Image);
            bmp.MakeTransparent(TransparentColor);
            int x = (this.Width - bmp.Width) / 2;
            int y = (this.Height - bmp.Height) / 2;
            e.Graphics.DrawImage(bmp, x, y);
        }
        base.OnPaint(e);
    }
}

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