C# 设置透明背景
时间: 2023-07-04 15:13:59 浏览: 63
在C#中设置窗体的透明背景可以通过设置窗体属性和使用Windows API来实现。
1. 通过设置窗体属性实现透明背景
将窗体的BackColor属性设置为Transparent即可实现透明背景。代码示例:
```
this.BackColor = Color.Transparent;
```
2. 使用Windows API实现透明背景
使用Windows API需要先引入user32.dll和gdi32.dll库文件,然后使用SetWindowLong和SetLayeredWindowAttributes函数来设置窗体的透明度和透明颜色。代码示例:
```
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
const int GWL_EXSTYLE = -20;
const int WS_EX_LAYERED = 0x80000;
const int LWA_ALPHA = 0x2;
private void SetTransparent()
{
int exstyle = GetWindowLong(this.Handle, GWL_EXSTYLE);
SetWindowLong(this.Handle, GWL_EXSTYLE, (uint)(exstyle | WS_EX_LAYERED));
SetLayeredWindowAttributes(this.Handle, 0, 128, LWA_ALPHA);
}
```
调用SetTransparent函数即可将窗体设置为透明背景。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)