65.9K
CodeProject 正在变化。 阅读更多。
Home

一个非常简单的 C# 异步定时消息框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.70/5 (9投票s)

2018年2月9日

CPOL

1分钟阅读

viewsIcon

38619

downloadIcon

771

一个非常简单但可定制的弹出消息框,在指定毫秒数后自动关闭。

引言

我需要一个定时消息框用于我正在编写的应用程序。与其重复造轮子,我四处寻找现有的解决方案。我找到了一些解决方案,但它们都比较复杂。我知道一定有更好的方法,所以我决定自己编写它。

事实证明,有一个非常简单的解决方案,可以在指定毫秒数后自动关闭消息框,并且是异步的。

它非常简单,与其描述它,我将直接在这里展示带有注释的代码。

代码

using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace PopUp
{
    /// <summary>
    /// A timed message box.
    /// </summary>
    /// <remarks>You can change some of the attributes of the underlying text box via the Set method.
    /// <para/>
    /// However, you can access the public TextBox object (as TextBox or tb) directly 
    /// and modify it in your code.
    /// </remarks>
    /// <example>
    /// Definition: static TimedPopUp popUp = new TimedPopUp(); <para />
    /// Usage: popUp.Set("Hello"[, delay][, width][, height][, fontName][, fontSize][, fontStyle]); 
    /// <para />
    /// popUp.Show();
    /// </example>
    partial class TimedPopUp : Form
    {
        public TimedPopUp()
        {
            InitializeComponent();
        }

        public TextBox TextBox { get => tb; }
        static int _waitTime;

        /// <summary>
        /// Initialize the values used to display the message box for a specific number of milliseconds.
        /// </summary>
        /// <param name="msg">The message to display in the text box.</param>
        /// <param name="caption">Optional: The title string of the text box.
        /// Default = "".</param>
        /// <param name="waitTime">Optional: The time to display the message in milliseconds.
        /// Default = 1000.</param>
        /// <param name="width">Optional: The width in pixels of the form.
        /// Default = 600.</param>
        /// <param name="height">Optional: The height in pixels of the form.
        /// Default = 100.</param>
        /// <param name="familyName">Optional: The font family name.
        /// Default = "Courier New".</param>
        /// <param name="emSize">Optional: The size of the font of the text box.
        /// Default = 12.</param>
        /// <param name="style">Optional: The sytyle of the font, viz., 
        /// Regular, Bold, Italic, Underline, or Strikeout.
        /// Default = FontStyle.Bold.</param>
        /// <remarks>Note that the Show method is used to actually display the message box.</remarks>
        public void Set(string msg, string caption = "", 
                        int waitTime = 1000, int width = 600, int height = 100,
                        string familyName = "Courier New", float emSize = 12, 
                        FontStyle style = FontStyle.Bold)
        {
            tb.Text = msg;
            tb.Font = new Font(familyName, emSize, style);
            this.Size = new Size(width, height);
            this.Text = caption;
            _waitTime = waitTime;
        }

        /// <summary>
        /// This is the method which is used to display the message box. 
        /// The Set method must be called prior to using this.
        /// </summary>
        /// <remarks>Note that this method effectively hides the normal Show method for the form.
        /// </remarks>
        async new public void Show()
        {
            // Invoke the normal form Show method to display the message box.
            base.Show();
            // The await operator makes this asynchronous 
            // so that the caller can continue to work while the message is displayed.
            await Task.Delay(_waitTime);
            // Once the wait time has run out the form is hidden.
            this.Hide();
        }
    }
}

如何使用

zip 文件中包含一个带有注释的示例项目,演示了程序的用法。解压缩该项目。在项目文件夹中,TestAsyncTimedMsgBox,您将看到项目 TimedPopUp.csTimedPopUp.designer.csTimedPopUp.resx。将它们复制到您的项目文件夹中。然后将表单 TimedPopUp.cs 添加到您的项目中。添加对消息框表单的引用,例如:

static TimedPopUp p = new TimedPopUp();

然后,每当您需要显示消息时,只需调用 p.Set() 然后 p.Show(),例如:

// Use the set method to initialize the settings with 
// non-default values prior to displaying the message. 
p.Set(String.Format("Count: {0}; waiting  for {1} ms.", count.ToString(), wait), 
      "Timed popup", wait, 400,
           style:System.Drawing.FontStyle.Bold);
// The Show method will display the message box for the specified number of milliseconds.
p.Show();

备注

您可以通过修改 Set 方法进一步轻松地自定义消息框的外观。但是,由于文本框 tb 被定义为 public 并且也可以通过 public 属性 TextBox 访问,因此您可以直接修改其属性,如包含的演示程序中所做的那样,例如:

// The following 2 statements are effectively equivalent. Both will set the backcolor of the message box.
// Note that tb is the name of the textbox on the TimedPopUp form and is public.
p.tb.BackColor = System.Drawing.Color.AliceBlue;
// It can also be referenced more generically as TextBox.
p.TextBox.BackColor = System.Drawing.Color.AliceBlue;

要求

为了支持 await 运算符,您必须使用 .NET Framework 4.5 或更高版本。

历史

  • 截至 2/1/18 的版本是 1.0.0.1
© . All rights reserved.