程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C# Windows Form Transparent Background Image大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决C# Windows Form Transparent BACkground Image?

开发过程中遇到C# Windows Form Transparent BACkground Image的问题如何解决?下面主要结合日常开发的经验,给出你关于C# Windows Form Transparent BACkground Image的解决方法建议,希望对你解决C# Windows Form Transparent BACkground Image有所启发或帮助;

You can use Layered Windows

Using a layered window can significantly improve perfoRMANce and visual effects for a window that has a complex shape, animates its shape, or wishes to use Alpha blending effects. The system automatically composes and repaints layered windows @R_197_6296@e windows of underlying applications. As a result, layered windows are rendered smoothly, without the flickering typical of complex window regions. In addition, layered windows can be partially translucent, that is, Alpha-blended.

Here is some code from msdn code gallery which demonstrates creaTing layered windows in windows Forms. It allows you to create a shaped splash screen and let you to move it by mouse.

Add PerPixelAlphaForm to the project @R_197_6296@en it’s enough to inherit from this form and call its SELEctBitmap and pass your png to the method to create a layered window.

C# Windows Form Transparent Background Image

#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.windows.Forms;
using System.Drawing.Imaging;
using System.Runtime.Interopservices;
#endregion
namespace CSWinFormlayeredWindow
{
    public partial class PerPixelAlphaForm : Form
    {
        public PerPixelAlphaForm()
        {
            this.Formborderstyle = System.windows.Forms.Formborderstyle.None;
            this.ShowInTaskbar = false;
            this.Startposition = FormStartposition.CenterScreen;
            this.Load += PerPixelAlphaForm_Load;
        }

        voID PerPixelAlphaForm_Load(object sender, EventArgs E)
        {
            this.topMost = true;
        }
        protected overrIDe CreateParams CreateParams
        {
            get
            {
                // Add the layered extended style (WS_EX_layered) to this window.
                CreateParams createParams = base.CreateParams;
                if(!DesignmodE)
                    createParams.ExStyle |= WS_EX_layered;
                return createParams;
            }
        }
        /// <sumMary>
        /// Let windows drag this window for us (thinks its hitTing the title 
        /// bar of the window)
        /// </sumMary>
        /// <param name="message"></param>
        protected overrIDe voID WndProc(ref message messagE)
        {
            if (message.Msg == WM_NCHITTEST)
            {
                // Tell windows that the user is on the title bar (caption)
                message.Result = (IntPtr)HTCAPTION;
            }
            else
            {
                base.WndProc(ref messagE);
            }
        }
        /// <sumMary>
        /// 
        /// </sumMary>
        /// <param name="bitmap"></param>
        public voID SELEctBitmap(Bitmap bitmap)
        {
            SELEctBitmap(bitmap, 255);
        }
        /// <sumMary>
        /// 
        /// </sumMary>
        /// <param name="bitmap">
        /// 
        /// </param>
        /// <param name="opacity">
        /// SpecifIEs an Alpha transparency value to be used on the entire source 
        /// bitmap. The sourceConstantAlpha value is combined with any per-pixel 
        /// Alpha values in the source bitmap. The value ranges from 0 to 255. If 
        /// you set sourceConstantAlpha to 0, it is assumed that your image is 
        /// transparent. When you only want to use per-pixel Alpha values, set 
        /// the sourceConstantAlpha value to 255 (opaquE).
        /// </param>
        public voID SELEctBitmap(Bitmap bitmap, int opacity)
        {
            // Does this bitmap contain an Alpha chAnnel?
            if (bitmap.pixelFormat != PixelFormat.Format32bppArgb)
            {
                throw new ApplicationException("The bitmap must be 32bpp with Alpha-chAnnel.");
            }

            // Get device contexts
            IntPtr screenDc = GetDC(IntPtr.Zero);
            IntPtr memDc = CreateCompatibleDC(screenDc);
            IntPtr hBitmap = IntPtr.Zero;
            IntPtr holdBitmap = IntPtr.Zero;

            try
            {
                // Get handle to the new bitmap and SELEct it into the current 
                // device context.
                hBitmap = bitmap.GetHbitmap(color.FromArgb(0));
                holdBitmap = SELEctObject(memDc, hBitmap);

                // Set parameters for layered window update.
                Size newSize = new Size(bitmap.WIDth, bitmap.Height);
                Point sourceLOCATIOn = new Point(0, 0);
                Point newLOCATIOn = new Point(this.left, this.top);
                BLENDFUNCTION blend = new BLENDFUNCTION();
                blend.blendop = AC_SRC_OVER;
                blend.blendFlags = 0;
                blend.sourceConstantAlpha = (bytE)opacity;
                blend.AlphaFormat = AC_SRC_Alpha;

                // update the window.
                updatelayeredWindow(
                    this.Handle,     // Handle to the layered window
                    screenDc,        // Handle to the screen DC
                    ref newLOCATIOn, // New screen position of the layered window
                    ref newSize,     // New size of the layered window
                    memDc,           // Handle to the layered window surface DC
                    ref sourceLOCATIOn, // LOCATIOn of the layer in the DC
                    0,               // color key of the layered window
                    ref blend,       // Transparency of the layered window
                    ulW_Alpha        // Use blend as the blend function
                    );
            }
            finally
            {
                // Release device context.
                ReleaseDC(IntPtr.Zero, screenDc);
                if (hBitmap != IntPtr.Zero)
                {
                    SELEctObject(memDc, holdBitmap);
                    deleteObject(hBitmap);
                }
                deleteDC(memDc);
            }
        }
        #region Native Methods and Structures

        const Int32 WS_EX_layered = 0x80000;
        const Int32 HTCAPTION = 0x02;
        const Int32 WM_NCHITTEST = 0x84;
        const Int32 ulW_Alpha = 0x02;
        const byte AC_SRC_OVER = 0x00;
        const byte AC_SRC_Alpha = 0x01;

        [StructLayout(LayoutKind.Sequential)]
        struct Point
        {
            public int32 x;
            public int32 y;

            public Point(Int32 x, Int32 y)
            { this.x = x; this.y = y; }
        }

        [StructLayout(LayoutKind.Sequential)]
        struct Size
        {
            public int32 cx;
            public int32 cy;

            public Size(Int32 cx, Int32 cy)
            { this.cx = cx; this.cy = cy; }
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        struct ARGB
        {
            public byte Blue;
            public byte Green;
            public byte Red;
            public byte Alpha;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        struct BLENDFUNCTION
        {
            public byte Blendop;
            public byte BlendFlags;
            public byte sourceConstantAlpha;
            public byte AlphaFormat;
        }

        [Dllimport("user32.dll", CharSet = CharSet.auto, SetLastError = truE)]
        [return: MarshalAs(UnmanagedType.bool)]
        static extern bool updatelayeredWindow(IntPtr hwnd, IntPtr hdcDst,
            ref Point pptDst, ref Size psize, IntPtr hdcSrc, ref Point pprSrc,
            Int32 crKey, ref BLENDFUNCTION pblend, Int32 DWFlags);

        [Dllimport("gdi32.dll", CharSet = CharSet.auto, SetLastError = truE)]
        static extern IntPtr CreateCompatibleDC(IntPtr hDC);

        [Dllimport("user32.dll", CharSet = CharSet.auto, SetLastError = truE)]
        static extern IntPtr GetDC(IntPtr hWnd);

        [Dllimport("user32.dll", CharSet = CharSet.auto, SetLastError = truE)]
        static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

        [Dllimport("gdi32.dll", CharSet = CharSet.auto, SetLastError = truE)]
        [return: MarshalAs(UnmanagedType.bool)]
        static extern bool deleteDC(IntPtr hdc);

        [Dllimport("gdi32.dll", CharSet = CharSet.auto, SetLastError = truE)]
        static extern IntPtr SELEctObject(IntPtr hDC, IntPtr hObject);

        [Dllimport("gdi32.dll", CharSet = CharSet.auto, SetLastError = truE)]
        [return: MarshalAs(UnmanagedType.bool)]
        static extern bool deleteObject(IntPtr hObject);

        #endregion
    }
}

public partial class Form4 : CSWinFormlayeredWindow.PerPixelAlphaForm
{
    public Form4()
    {
        InitializeComponent();
        this.SELEctBitmap(PropertIEs.resources.splash);
    }
}

The original answer was based on turning double buffer off and overrIDingOnPaintBACkground and drawing the image without calling base method. The answer had a kNown issue; while the form was moveless it was working well but if form was moving or the window behind the form was changed the window was not updating. You can see prevIoUs code in revisions. The current edit which is completely based on an MSDN code doesn’t have any kNown issue.

解决方法

When I tried from with transparent BACkground,it’s not completely
transparent. I tried two code blocks for this issue. First i tried like this
code:

 public Form1()
    {
        InitializeComponent();
        SetStyle(ControlStyles.SupportsTransparentBACkColor,truE);
        this.BACkColor = Color.Transparent;
        this.FormBorderstyle = FormBorderstyle.None;
        //this.WindowState = System.Windows.Forms.FormWindowState.Maximized;

    }

it look like this picture;

C# Windows Form Transparent Background Image

Then i found some different codes and tried ike this;

 public Form1()
    {
        InitializeComponent();
        this.TransparencyKey = Color.White;
        this.BACkColor = Color.White;
        this.FormBorderstyle = FormBorderstyle.None;
        this.WindowState = System.Windows.Forms.FormWindowState.Maximized;

    }

@R_197_6296@is looks like this picture;

C# Windows Form Transparent Background Image

You can see logo with a white border. I want to show only .png Logo completely
transparent. what should i do? How can do this?

Here is my Logo image as .png;

C# Windows Form Transparent Background Image

大佬总结

以上是大佬教程为你收集整理的C# Windows Form Transparent Background Image全部内容,希望文章能够帮你解决C# Windows Form Transparent Background Image所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Windows