C#中怎样才能让form窗体的背景色,支持Transparent

 我来答
nqildp
2011-01-27 · TA获得超过1419个赞
知道小有建树答主
回答量:1159
采纳率:0%
帮助的人:982万
展开全部
虽然不是无法实现,但比较麻烦。
因为opacity属性会让窗体上所有的控件都变成透明的,所以我们可以这样办。

代码如下:
Form f = new Form(); //创建一个新窗体
Label lab = new Label(); //要显示的文本
void MainFormLoad(object sender, EventArgs e)
{
f.FormBorderStyle = FormBorderStyle.None; //设置窗体无边框
f.ShowInTaskbar = false;
f.BackColor = Color.Red;f.TransparencyKey = f.BackColor; //让窗体透明
lab.Text = "我是在透明窗体上的不透明文本!";
lab.BackColor = Color.Transparent; //背景色透明
lab.Location = new Point(100,150); //调整在窗体上的位置
f.Controls.Add(lab);
f.TopLevel = true;
f.Show();
}

void MainFormMove(object sender, EventArgs e)
{
f.Location = this.Location;
}

时间仓促,这段代码仍然不是很完美,需要你自己仔细修复一下。
wangbenson
2011-01-26 · TA获得超过161个赞
知道答主
回答量:283
采纳率:0%
帮助的人:197万
展开全部
使用API函数
class WinAPI
{
[DllImport("user32.dll")]
public extern static IntPtr GetDesktopWindow();

[DllImport("user32.dll")]
public extern static bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
public static uint LWA_COLORKEY = 0x00000001;
public static uint LWA_ALPHA = 0x00000002;

[DllImport("user32.dll")]
public extern static uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
[DllImport("user32.dll")]
public extern static uint GetWindowLong(IntPtr hwnd, int nIndex);

public enum WindowStyle : int
{
GWL_EXSTYLE = -20
}

public enum ExWindowStyle : uint
{
WS_EX_LAYERED = 0x00080000
}

}

----------------------------------------------------------------------------------
namespace TransForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
this.SetWindowTransparent(100);
}
private void SetWindowTransparent(byte bAlpha)
{
try
{
WinAPI.SetWindowLong(this.Handle, (int)WinAPI.WindowStyle.GWL_EXSTYLE,
WinAPI.GetWindowLong(this.Handle, (int)WinAPI.WindowStyle.GWL_EXSTYLE) | (uint)WinAPI.ExWindowStyle.WS_EX_LAYERED);

WinAPI.SetLayeredWindowAttributes(this.Handle, 0, bAlpha, WinAPI.LWA_COLORKEY | WinAPI.LWA_ALPHA);
}
catch
{
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;

cp.Parent = WinAPI.GetDesktopWindow();
cp.ExStyle = 0x00000080 | 0x00000008;//WS_EX_TOOLWINDOW | WS_EX_TOPMOST

return cp;
}
}
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式