C# WinForm实现定时刷新浏览器并累加Label数值
Got it, let's walk through building this feature set step by step. I'll cover both the form design and code logic to make sure everything works as expected.
1. Form Design Setup
First, drag these controls onto your Windows Form from the Toolbox:
- TextBox: Name it
textBoxDuration(for entering timer duration in seconds) - Button: Name it
btnStartStop(set initial text to "Start Timer") - WebBrowser: Name it
webBrowser1 - Label: Name it
labelCount(set initial text to "0" and add a descriptive label like "Refresh Count: " next to it for clarity)
2. Code Implementation
Add the following code to your form's code-behind file:
Form-Level Variables
We'll use these to track timer state, refresh count, and whether a refresh was triggered by the timer:
private System.Windows.Forms.Timer refreshTimer; private int refreshCount = 0; private bool isTimerInitiatedRefresh = false;
Form Constructor
Initialize the timer and set up event handlers:
public YourFormName() { InitializeComponent(); // Initialize timer and attach tick event refreshTimer = new Timer(); refreshTimer.Tick += RefreshTimer_Tick; // Set initial count display labelCount.Text = refreshCount.ToString(); // Optional: Load a default URL on form startup webBrowser1.Navigate("https://example.com"); }
Start/Stop Button Click Handler
This toggles the timer state and validates user input:
private void btnStartStop_Click(object sender, EventArgs e) { if (!refreshTimer.Enabled) { // Parse and validate duration input if (int.TryParse(textBoxDuration.Text, out int seconds) && seconds > 0) { // Convert seconds to milliseconds (Timer uses ms for interval) refreshTimer.Interval = seconds * 1000; refreshTimer.Start(); btnStartStop.Text = "Stop Timer"; } else { MessageBox.Show("Please enter a valid positive number for the timer duration (in seconds)."); } } else { // Stop timer and reset button text refreshTimer.Stop(); btnStartStop.Text = "Start Timer"; } }
Timer Tick Event
Triggers the WebBrowser refresh when the timer times out:
private void RefreshTimer_Tick(object sender, EventArgs e) { // Mark this refresh as timer-initiated isTimerInitiatedRefresh = true; webBrowser1.Refresh(); }
WebBrowser Document Completed Event
Increments the count only after a timer-triggered refresh finishes loading:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { // Only increment count if refresh was started by the timer if (isTimerInitiatedRefresh) { refreshCount++; labelCount.Text = refreshCount.ToString(); // Reset flag to exclude initial loads/manual refreshes isTimerInitiatedRefresh = false; } }
Key Notes
- Input Safety: The code validates that the user enters a positive integer, preventing crashes from invalid inputs.
- Accurate Counting: The
isTimerInitiatedRefreshflag ensures we only count timer-triggered refreshes, not initial page loads or manual refreshes. - Intuitive UI: The button toggles between "Start Timer" and "Stop Timer" to reflect the current state.
Don't forget to wire up the btnStartStop_Click and webBrowser1_DocumentCompleted events—you can do this via the Properties window in Visual Studio or manually in the constructor if you prefer.
内容的提问来源于stack exchange,提问作者Chris edward

