You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现复制文本到剪贴板后显示1-2秒平滑淡出的弹窗提示?

问题分析

你原代码的核心问题有两个:

  • MessageBox.Show()是模态弹窗,会直接阻塞当前线程,必须等用户手动关闭弹窗后,后续的定时器代码才会执行,完全达不到自动关闭的效果。
  • MessageBox类根本没有静态的Close()方法,这行代码会直接编译报错。

要实现「自动平滑淡出的提示」,不能用MessageBox,得自己做一个轻量的非模态提示窗口。

解决方案

我们可以创建一个无边框的小型提示窗体,设置它置顶显示,然后用两个定时器配合:一个控制延迟多久开始淡出,另一个控制淡出的平滑动画,最后自动关闭窗口。

完整代码实现

直接在你的窗体类中添加以下代码即可:

private void btnCopyInformation_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrWhiteSpace(richTextBox1.Text))
    {
        // 复制内容到剪贴板
        Clipboard.SetText(richTextBox1.Text);
        
        // 显示自动淡出的提示
        ShowAutoFadeTip("已复制到剪贴板");
    }
    else
    {
        MessageBox.Show("RichTextBox为空,无法复制。");
    }
}

private void ShowAutoFadeTip(string tipText)
{
    // 创建提示窗体
    Form tipForm = new Form();
    tipForm.FormBorderStyle = FormBorderStyle.None;
    tipForm.StartPosition = FormStartPosition.CenterParent;
    tipForm.BackColor = Color.FromArgb(245, 245, 245);
    tipForm.Opacity = 1;
    tipForm.Size = new Size(220, 65);
    tipForm.TopMost = true;

    // 添加提示文本标签
    Label tipLabel = new Label();
    tipLabel.Text = tipText;
    tipLabel.Dock = DockStyle.Fill;
    tipLabel.TextAlign = ContentAlignment.MiddleCenter;
    tipLabel.Font = new Font("微软雅黑", 10.5f);
    tipForm.Controls.Add(tipLabel);

    // 延迟定时器:1.5秒后开始淡出(可调整Interval值改变延迟时间)
    Timer delayTimer = new Timer();
    delayTimer.Interval = 1500;
    delayTimer.Tick += (s, args) =>
    {
        delayTimer.Stop();
        delayTimer.Dispose();

        // 淡出定时器:每50ms降低一次透明度,实现平滑效果
        Timer fadeTimer = new Timer();
        fadeTimer.Interval = 50;
        fadeTimer.Tick += (fs, fargs) =>
        {
            if (tipForm.Opacity > 0)
            {
                tipForm.Opacity -= 0.08;
            }
            else
            {
                fadeTimer.Stop();
                fadeTimer.Dispose();
                tipForm.Close();
                tipForm.Dispose();
            }
        };
        fadeTimer.Start();
    };

    // 显示提示并启动定时器
    tipForm.Show(this);
    delayTimer.Start();
}

代码说明

  • 自定义提示窗体是非模态的,不会阻塞主线程,定时器能正常按预期执行。
  • 两个定时器分工明确:第一个负责等待指定时间(1-2秒可自行调整),第二个负责逐步降低窗体透明度,实现平滑淡出效果。
  • 提示窗体设置TopMost = true,确保能显示在所有窗口最上层,不会被遮挡。

内容的提问来源于stack exchange,提问作者Shien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 23:29:54