重要
StatusStrip 和 ToolStripStatusLabel 控件替换并添加 StatusBar 和 StatusBarPanel 控件的功能;但是,如果选择,则保留 StatusBar 和 StatusBarPanel 控件以实现向后兼容性和将来使用。
程序通常需要在运行时根据应用程序状态或其他用户交互的变化,动态更新状态栏面板的内容。 这是向用户发出信号的一种常见方法,用于指示 CAPS LOCK、NUM LOCK 或 SCROLL LOCK 键已启用,或者提供日期或时间作为便利的参考。
在以下示例中,你将使用 StatusBarPanel 类的实例来托管时钟。
准备更新状态栏
创建新的 Windows 窗体。
向窗体添加一个 StatusBar 控件。 有关详细信息,请参阅如何:向 Windows 窗体添加控件。
将状态栏面板添加到 StatusBar 控件。 有关详细信息,请参阅 如何:将面板添加到 StatusBar 控件。
对于添加到窗体中的 StatusBar 控件,请将 ShowPanels 属性设置为
true
。将 Windows 窗体 Timer 组件添加到窗体。
注释
Windows 窗体 System.Windows.Forms.Timer 组件专为 Windows 窗体环境设计。 如果需要适合服务器环境的计时器,请参阅 Server-Based 计时器简介。
将 Enabled 属性设置为
true
。
实现计时器以更新状态栏
将以下代码插入 Timer 组件的事件处理程序中,以更新 StatusBar 控件的面板。
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick StatusBar1.Panels(0).Text = Now.ToShortTimeString End Sub
private void timer1_Tick(object sender, System.EventArgs e) { statusBar1.Panels[0].Text = DateTime.Now.ToShortTimeString(); }
private: System::Void timer1_Tick(System::Object ^ sender, System::EventArgs ^ e) { statusBar1->Panels[0]->Text = DateTime::Now.ToShortTimeString(); }
此时,你已准备好运行应用程序,并观察在状态栏面板中运行的时钟。
测试应用程序
调试应用程序并按 F5 运行它。 有关调试的详细信息,请参阅 Visual Studio中的
调试。 注释
大约 30 秒之后,时钟才会出现在状态栏上。 这是为了获得最准确的时间。 相反,为了更快地显示时钟,可以减小在上一过程中步骤 7 中设置的 Interval 属性的值。