【问题标题】:How to make window forms to be transperent?如何使窗体透明?
【发布时间】:2012-03-04 21:38:47
【问题描述】:
我想用我的 winform 应用程序实现下一个场景:
当应用程序启动时,它会停留在桌面上。如果用户有一段时间没有使用该应用程序,例如 1 分钟,我希望它失去它的透明度(主窗体的透明度降低到一半)
如果再次使用应用程序(焦点、鼠标悬停...),主窗体的透明度值将设置回 100%。
那么实际上我需要从哪里开始?
我假设我需要在不同的线程中使用一个计时器来触发一些事件,以防万一它达到 1 分钟,但这里的问题是,我将如何(以及哪些)在不同的线程中监听来自的事件(我用于计时器)
谢谢
【问题讨论】:
标签:
winforms
timer
mouseevent
transparency
keyboard-events
【解决方案2】:
正如 Lars 所说,表单上有 Opacity 属性。
要在表单处于非活动状态时将不透明度设置为一半,您需要处理 Deactivated 或 Application.Idle 事件。在此启动一个计时器,它将向表单(在 UI 线程上)发送回消息以实际设置值。
private void Form_Deactivate(object sender, EventArgs e)
{
this.inactiveTimer = new Timer();
this.inactiveTimer.Interval = 1000;
this.inactiveTimer.Tick += this.InactiveTimer_Tick;
// Start timer
this.inactiveTimer.Start();
}
private void InactiveTimer_Tick(object sender, EventArgs e)
{
// This is being handled on the UI thread
this.Opacity = 0.5;
this.inactiveTimer.Stop();
}
如果您希望表单逐渐获得透明度,请将计时器间隔设置为较小的量(例如 100 毫秒),并在每个刻度上逐步降低透明度。然后当不透明度达到 0.5 时停止计时器。
当表单再次变为活动状态时会触发Activated 事件:
private void Form_Activate(object sender, EventArgs e)
{
this.Opacity = 1.0;
// Stop the timer for the cases where the user reactivates the app
this.inactiveTimer.Stop();
}
您可能需要捕获其他事件,例如 SizeChanged,以确保不透明度正确设置回 1(当表单从最小化状态恢复时触发)和 ResizeEnd。