It sounds like the stateTimer object is being declared in the scope of
your start button code. You'll need to declare it more global in the
scope of your class so that the stop button code has visibility of
the object.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
namespace EnvVar
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class frmMain : System.Windows.Forms.Form
{
System.Threading.Timer oTimer; //visible to entire class code
int iCount;
private System.Windows.Forms.Button StartButton;
private System.Windows.Forms.Button StopButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public frmMain()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent
call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.StartButton = new System.Windows.Forms.Button();
this.StopButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// StartButton
//
this.StartButton.Location = new System.Drawing.Point(208,
192);
this.StartButton.Name = "StartButton";
this.StartButton.TabIndex = 0;
this.StartButton.Text = "button1";
this.StartButton.Click += new
System.EventHandler(this.StartButton_Click);
//
// StopButton
//
this.StopButton.Location = new System.Drawing.Point(192,
232);
this.StopButton.Name = "StopButton";
this.StopButton.TabIndex = 1;
this.StopButton.Text = "button2";
this.StopButton.Click += new
System.EventHandler(this.StopButton_Click);
//
// frmMain
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.StopButton);
this.Controls.Add(this.StartButton);
this.Name = "frmMain";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new frmMain());
}
private void StartButton_Click(object sender, System.EventArgs
e)
{
oTimer = new System.Threading.Timer( new
TimerCallback(ab), null, 1000, 1000 );
}
private void StopButton_Click(object sender, System.EventArgs
e)
{
oTimer.Dispose();
}
public void ab( Object state )
{
iCount++;
}
}
}