当前位置:文档之家› c#_ms_chart_控件使用方法汇总(附统计图)

c#_ms_chart_控件使用方法汇总(附统计图)

c#_ms_chart_控件使用方法汇总(附统计图)
c#_ms_chart_控件使用方法汇总(附统计图)

c# ms chart 控件使用方法

第一个简单的chart:创建曲线图

chart1.Series.Clear();

Series series = new Series("Spline");

series.ChartType = SeriesChartType.Spline;

series.BorderWidth = 3;

series.ShadowOffset = 2;

// Populate new series with data

series.Points.AddY(67);

series.Points.AddY(57);

series.Points.AddY(83);

series.Points.AddY(23);

series.Points.AddY(70);

series.Points.AddY(60);

series.Points.AddY(90);

series.Points.AddY(20);

// Add series into the chart's series collection

chart1.Series.Add(series);

同时显示2条曲线

// Populate series with random data

Random random = new Random();

for (int pointIndex = 0; pointIndex < 10;pointIndex++)

{

Chart1.Series["Series1"].Points.AddY(random.Next(45, 95)); Chart1.Series["Series2"].Points.AddY(random.Next(5, 75)); }

// Set series chart type

Chart1.Series["Series1"].ChartType = SeriesChartType.Line; Chart1.Series["Series2"].ChartType = SeriesChartType.Spline;

// Set point labels

Chart1.Series["Series1"].IsValueShownAsLabel = true;

Chart1.Series["Series2"].IsValueShownAsLabel = true;

// Enable X axis margin

Chart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = true;

// Enable 3D, and show data point marker lines

Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true; Chart1.Series["Series1"]["ShowMarkerLines"] = "True";

Chart1.Series["Series2"]["ShowMarkerLines"] = "True";

显示column类型图,柱状图

// Create new data series and set it's visual attributes

Chart1.Series.Clear();

Series series = new Series("FlowRead");

series.ChartType = SeriesChartType.Column;

series.BorderWidth = 3;

series.ShadowOffset = 2;

// Populate new series with data

series.Points.AddY(67);

series.Points.AddY(57);

series.Points.AddY(83);

series.Points.AddY(23);

series.Points.AddY(70);

series.Points.AddY(60);

series.Points.AddY(90);

series.Points.AddY(20);

// Add series into the chart's series collection

Chart1.Series.Add(series);

很多点,效率还可以

// Fill series data

double yValue = 50.0;

Random random = new Random();

for (int pointIndex = 0; pointIndex < 20000;pointIndex++)

{

yValue = yValue + (random.NextDouble() * 10.0 - 5.0);

Chart1.Series["Series1"].Points.AddY(yValue);

}

// Set fast line chart type

Chart1.Series["Series1"].ChartType = SeriesChartType.FastLine;

日期,xy类型

// Create a new random number generator

Random rnd = new Random();

// Data points X value is using current date DateTime date = DateTime.Now.Date;

// Add points to the stock chart series

for (int index = 0; index < 10; index++)

{

Chart1.Series["Series1"].Points.AddXY( date, // X value is a date

rnd.Next(40,50)); //Close Y value

// Add 1 day to our X value

date = date.AddDays(1);

int-int的xy数据绘图

// Create a new random number generator

Random rnd = new Random();

// Add points to the stock chart series

for (int index = 0; index < 10; index++)

{

Chart1.Series["Series1"].Points.AddXY(

rnd.Next(10,90), // X value is a date rnd.Next(40,50)); //Close Y value

数据库数据,datetime-int类型

Chart1.Series.Clear();

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");

OleDbCommand cmd = conn.CreateCommand();

conn.Open();

https://www.doczj.com/doc/2e186129.html,mandText = "select 时间,序号from pub_log_read order by 序号asc";

//DataSet ds = new DataSet();

//OleDbDataAdapter da = new OleDbDataAdapter();

//da.SelectCommand = cmd;

//da.Fill(ds, "tbscore");

OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

Chart1.DataBindTable(dr, "时间");

dr.Close();

数据库数据2,string-int类型

Chart1.Series.Clear();

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");

OleDbCommand cmd = conn.CreateCommand();

conn.Open();

https://www.doczj.com/doc/2e186129.html,mandText = "select 账号,count(账号) as 次数from pub_log_read group by 账号order by 账号asc";

//DataSet ds = new DataSet();

//OleDbDataAdapter da = new OleDbDataAdapter();

//da.SelectCommand = cmd;

//da.Fill(ds, "tbscore");

OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

Chart1.DataBindTable(dr, "账号");

dr.Close();

数据库绑定3-string-int型

Chart1.Series.Clear();

Chart1.Series.Add("Series1");

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");

OleDbCommand cmd = conn.CreateCommand();

https://www.doczj.com/doc/2e186129.html,mandText = "select 账号,count(账号) as 次数from pub_log_read group by 账号order by 账号asc";

conn.Open();

DataSet ds = new DataSet();

OleDbDataAdapter da = new OleDbDataAdapter();

da.SelectCommand = cmd;

da.Fill(ds, "tbscore");

Chart1.DataSource = ds;

Chart1.Series["Series1"].XValueMember = "账号";

Chart1.Series["Series1"].YValueMembers = "次数";

// Data bind to the selected data source

Chart1.DataBind();

conn.Close();

数据库4,只绑定y

Chart1.Series.Clear();

Chart1.Series.Add("序号");

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");

OleDbCommand cmd = conn.CreateCommand();

conn.Open();

https://www.doczj.com/doc/2e186129.html,mandText = "select 序号from pub_log_read order by 序号asc";

//DataSet ds = new DataSet();

//OleDbDataAdapter da = new OleDbDataAdapter();

//da.SelectCommand = cmd;

//da.Fill(ds, "tbscore");

OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

Chart1.Series[0].Points.DataBindY(dr);

dr.Close();

数据库5,绑定xy

Chart1.Series.Clear();

Chart1.Series.Add("序号");

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");

OleDbCommand cmd = conn.CreateCommand();

conn.Open();

https://www.doczj.com/doc/2e186129.html,mandText = "select 账号,count(账号) as 次数from pub_log_read group by 账号order by 账号desc";

//DataSet ds = new DataSet();

//OleDbDataAdapter da = new OleDbDataAdapter();

//da.SelectCommand = cmd;

//da.Fill(ds, "tbscore");

OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

Chart1.Series[0].Points.DataBindXY(dr,"账号",dr,"次数");

dr.Close();

数据库6,支持显示参数

Chart1.Series.Clear();

Chart1.Series.Add("S1");

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");

OleDbCommand cmd = conn.CreateCommand();

conn.Open();

https://www.doczj.com/doc/2e186129.html,mandText = "SELECT * FROM REPSALES WHERE Year=2004";

//DataSet ds = new DataSet();

//OleDbDataAdapter da = new OleDbDataAdapter();

//da.SelectCommand = cmd;

//da.Fill(ds, "tbscore");

OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

Chart1.Series[0].Points.DataBind(dr, "name", "sales", "Tooltip=Year,

Label=Commissions{C2}");

dr.Close();

数据库7,支持多line

Chart1.Series.Clear();

Chart1.Series.Add("S1");

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

Application.StartupPath + @"\db.mdb" + ";Persist Security Info=False");

OleDbCommand cmd = conn.CreateCommand();

conn.Open();

https://www.doczj.com/doc/2e186129.html,mandText = "SELECT * FROM REPSALES";

//DataSet ds = new DataSet();

//OleDbDataAdapter da = new OleDbDataAdapter();

//da.SelectCommand = cmd;

//da.Fill(ds, "tbscore");

OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

Chart1.DataBindCrossTable(dr, "Name", "Year", "Sales", "Label=Commissions{C}");

dr.Close();

数据库8,按照行添加数据

// Resolve the address to the Access database

stringfileNameString = this.MapPath(".");

fileNameString += "..\\..\\..\\data\\chartdata.mdb";

//Initialize a connectionstring

stringmyConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileNameString;

// Definethe databasequery

stringmySelectQuery="SELECT * FROM SALESCOUNTS;";

// Createa database connection object using the connectionstring

OleDbConnection myConnection = newOleDbConnection(myConnectionString);

// Create adatabase command on the connection usingquery

OleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);

// Open theconnection

myCommand.Connection.Open();

//Initializes a new instance of the OleDbDataAdapter class

OleDbDataAdapter myDataAdapter = new OleDbDataAdapter();

myDataAdapter.SelectCommand = myCommand;

//Initializes a new instance of the DataSet class

DataSetmyDataSet = new DataSet();

// Addsrows in the DataSet

myDataAdapter.Fill(myDataSet,"Query");

foreach(DataRow row in myDataSet.Tables["Query"].Rows)

{

// For each Row add a new series

string seriesName = row["SalesRep"].ToString();

Chart1.Series.Add(seriesName);

Chart1.Series[seriesName].ChartType = SeriesChartType.Line;

Chart1.Series[seriesName].BorderWidth = 2;

for(int colIndex = 1; colIndex

// For each column (column 1 and onward) add the value as apoint

string columnName =myDataSet.Tables["Query"].Columns[colIndex].ColumnName; int YVal = (int) row[columnName];

Chart1.Series[seriesName].Points.AddXY(columnName, YVal);

}

}

DataGrid.DataSource = myDataSet;

DataGrid.DataBind();

// Closesthe connection to the data source. This is the preferred

// method ofclosing any open connection.

myCommand.Connection.Close();

使用xml数据

// resolve the address to the XML document

stringfileNameString = this.MapPath(".");

stringfileNameSchema = this.MapPath(".");

fileNameString += "..\\..\\..\\data\\data.xml";

fileNameSchema += "..\\..\\..\\data\\data.xsd";

//Initializes a new instance of the DataSet class

DataSetcustDS = new DataSet();

// Read XMLschema into the DataSet.

custDS.ReadXmlSchema( fileNameSchema );

// ReadXML schema and data into the DataSet.

custDS.ReadXml( fileNameString );

//Initializes a new instance of the DataView class

DataViewfirstView = new DataView(custDS.Tables[0]);

// Sincethe DataView implements and IEnumerable, pass the reader directlyinto

// theDataBindTable method with the name of the column used for the Xvalue.

Chart1.DataBindTable(firstView, "Name");

使用excel数据

// resolve the address to the Excel file

stringfileNameString = this.MapPath(".");

fileNameString += "..\\..\\..\\data\\ExcelData.xls";

// Createconnection object by using the preceding connection string.

string sConn= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

fileNameString + ";Extended Properties="Excel8.0;HDR=YES"";

OleDbConnection myConnection = new OleDbConnection( sConn );

myConnection.Open();

// Thecode to follow uses a SQL SELECT command to display the data fromthe worksheet.

// Createnew OleDbCommand to return data from worksheet.

OleDbCommandmyCommand = new OleDbCommand( "Select * From

[data1$A1:E25]",myConnection );

// createa databasereader

OleDbDataReader myReader

=myCommand.ExecuteReader(CommandBehavior.CloseConnection);

//Populate the chart with data in the file

Chart1.DataBindTable(myReader, "HOUR");

// closethe reader and the connection

myReader.Close();

myConnection.Close();

使用csv数据

// Filename of the CSV file

string file= "DataFile.csv";

// Getthe path of the CSV file

string path= this.MapPath(".");

path +="..\\..\\..\\data\";

// Createa select statement and a connection string.

stringmySelectQuery = "Select * from " + file;

stringConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+

path+ ";Extended Properties="Text;HDR=No;FMT=Delimited"";

OleDbConnection myConnection = new OleDbConnection(ConStr);

// Createa database command on the connection using query

OleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);

// Openthe connection and create the reader

myCommand.Connection.Open();

OleDbDataReader myReader

=myCommand.ExecuteReader(CommandBehavior.CloseConnection);

// Column1 is a time value, column 2 is a double

// Databindthe reader to the chart using the DataBindXY method

Chart1.Series[0].Points.DataBindXY(myReader, "1", myReader,"2");

// Closeconnection and data reader

myReader.Close();

myConnection.Close();

数组绘图

// Initialize an array of doubles

double[] yval = { 2, 6, 4, 5, 3 };

// Initialize an array of strings

string[] xval = { "Peter", "Andrew", "Julie", "Mary", "Dave" };

// Bind the double array to the Y axis points of the Default dataseries

Chart1.Series["Series1"].Points.DataBindXY(xval, yval);

数据库9,dataview// Resolve the address to the Access database

stringfileNameString = this.MapPath(".");

fileNameString += "..\\..\\..\\data\\chartdata.mdb";

//Initialize a connectionstring

stringmyConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileNameString;

// Definethe databasequery

stringmySelectQuery="SELECT * FROM REPS;";

// Createa database connection object using the connectionstring

OleDbConnection myConnection = newOleDbConnection(myConnectionString);

// Create adatabase command on the connection usingquery

OleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);

// Open theconnection

myCommand.Connection.Open();

//Initializes a new instance of the OleDbDataAdapter class

OleDbDataAdapter custDA = new OleDbDataAdapter();

custDA.SelectCommand = myCommand;

//Initializes a new instance of the DataSet class

DataSetcustDS = new DataSet();

// Addsrows in the DataSet

custDA.Fill(custDS, "Customers");

//Initializes a new instance of the DataView class

DataViewfirstView = new DataView(custDS.Tables[0]);

// Sincethe DataView implements IEnumerable, pass the dataview directlyinto

// the DataBind method with thename of the Columns selected in thequery

Chart1.Series["Default"].Points.DataBindXY(firstView,"Name",firstView, "Sales");

// Closesthe connection to the data source. This is the preferred

// method of closing any openconnection.

myCommand.Connection.Close();

指定坐标轴的数据显示范围

// Create a new random number generator

Random rnd = new Random();

// Add points to the stock chart series

for (int index = 0; index < 10; index++)

{

Chart1.Series["Series1"].Points.AddXY(

rnd.Next(10,90), // X value is a date

rnd.Next(40,50)); //Close Y value

}

Chart1.ChartAreas[0].AxisY.Minimum = 40;

Chart1.ChartAreas[0].AxisY.Maximum = 50;

数据排序// Use point index for drawing the chart

Chart1.Series["Series1"].IsXValueIndexed = true;

// Sortseries points by second Y value

Chart1.DataManipulator.Sort(PointSortOrder.Ascending, "Y2","Series1");

查找数据最大值和最小值

// Find point with maximum Y value and change color

DataPointmaxValuePoint =Chart1.Series["Series1"].Points.FindMaxValue(); maxValuePoint.Color = Color.FromArgb(255, 128, 128);

// Findpoint with minimum Y value and change color

DataPointminValuePoint =Chart1.Series["Series1"].Points.FindMinValue(); minValuePoint.Color = Color.FromArgb(128, 128, 255);

pie显示交互

private void Page_Load(object sender, System.EventArgs e)

{

// Addseries to the chart

Seriesseries = Chart1.Series.Add("My series");

// Setseries and legend tooltips

series.ToolTip = "#VALX: #VAL{C} million";

series.LegendToolTip = "#PERCENT";

series.PostBackValue = "#INDEX";

series.LegendPostBackValue = "#INDEX";

// Populateseries data

double[] yValues = {65.62, 75.54, 60.45, 34.73, 85.42, 32.12, 55.18, 67.15,56.24, 23.65};

string[] xValues = {"France", "Canada", "Germany", "USA", "Italy", "Russia","China", "Japan", "Sweden", "Spain" };

series.Points.DataBindXY(xValues, yValues);

// Setseries visual attributes

series.Type= SeriesChartType.Pie;

series.ShadowOffset = 2;

series.BorderColor = Color.DarkGray;

series.CustomAttributes = "LabelStyle=Outside";

}

protected void Chart1_Click(object sender, ImageMapEventArgse)

{

intpointIndex = int.Parse(e.PostBackValue);

Seriesseries = Chart1.Series["My series"];

if(pointIndex >= 0 &&pointIndex < series.Points.Count)

{

series.Points[pointIndex].CustomProperties +="Exploded=true";

}

}

chart点击事件///

/// Page Load event handler.

///

protected void Page_Load(object sender, System.EventArgs e)

{

this.Chart1.Click += new ImageMapEventHandler(Chart1_Click);

// directusing of PostBackValue

foreach(Series series in this.Chart1.Series)

{

series.PostBackValue = "series:" + https://www.doczj.com/doc/2e186129.html, + ",#INDEX";

}

// transferof click coordinates. getCoordinates is a javascriptfunction.

stringpostbackScript =ClientScript.GetPostBackEventReference(this.Chart1,"chart:@");

this.Chart1.Attributes["onclick"] = postbackScript.Replace("@'", "'+ getCoordinates(event)"); }

///

/// Handles the Click event of the Chart1 control.

///

/// The sourceof the event.

///

name="e">Theinstance containing the eventdata.

protected void Chart1_Click(object sender, ImageMapEventArgse)

{

this.Chart1.Titles["ClickedElement"].Text = "Nothing";

string[]input = e.PostBackValue.Split(':');

if(input.Length == 2)

{

string[] seriesData = input[1].Split(',');

if (input[0].Equals("series"))

{

this.Chart1.Titles["ClickedElement"].Text = "Last Clicked Element:" + seriesData[0] + " - Data Point #" + seriesData[1];

}

else if (input[0].Equals("chart"))

{

// hit test of X and Y click point

HitTestResult hitTestResult

=this.Chart1.HitTest(Int32.Parse(seriesData[0]),Int32.Parse(seriesData[1]));

if (hitTestResult != null)

{

this.Chart1.Titles["ClickedElement"].Text = "Last Clicked Element:" + hitTestResult.ChartElementType.ToString();

}

}

}

}

https://www.doczj.com/doc/2e186129.html, AJAX入门系列:Timer控件简单使用

https://www.doczj.com/doc/2e186129.html, AJAX入门系列:Timer控件简单使用 本文主要通过一个简单示例,让Web页面在一定的时间间隔内局部刷新,来学习一下https://www.doczj.com/doc/2e186129.html, AJAX中的服务端Timer控件的简单使用。 主要内容 Timer控件的简单使用 1.添加新页面并切换到设计视图。 2.如果页面没有包含ScriptManager控件,在工具箱的AJAX Extensions标签下双击ScriptManager控件添加到页面中。 3.单击ScriptManager控件并双击UpdatePanel控件添加到页面中。

4.在UpdatePanel控件内单击并双击Timer控件添加到UpdatePanel中。Timer控件可以作为UpdatePanel的触发器不管是否在UpdatePanel中。 5.设置Interval属性为10000。Interval属性的单位是毫秒,所以我们设置为10000,相当于10秒钟刷新一次。 6.在UpdatePanel控件中添加一个Label控件。

7.设置Label控件的Text属性为“Panel not refreshed yet ”。确保Label控件添加在了UpdatePanel控件里面。 8.在UpdatePanel之外再添加一个Label控件。确保第二个Label控件在UpdatePanel的外面。 9.双击Timer控件添加Tick事件处理,在事件处理中设置Label1的Text属性为当前时间。 protected void Timer1_Tick(object sender, EventArgs e)

{ Label1.Text = "Panel refreshed at: " + DateTime.Now.ToLongTimeString(); } 10.在Page_Load事件中添加代码设置Label2的Text属性为页面创建时间,如下代码所示: protected void Page_Load(object sender, EventArgs e) { Label2.Text = "Page created at: " + DateTime.Now.ToLongTimeString(); } 11.切换到代码视图,确保代码如下所示: protected void Page_Load(object sender, EventArgs e) { Label2.Text = "Page created at: " + DateTime.Now.ToLongTimeString(); } protected void Timer1_Tick(object sender, EventArgs e) { Label1.Text = "Panel refreshed at: " + DateTime.Now.ToLongTimeString(); } 12.保存并按Ctrl + F5运行 13.等待10秒钟后可以看到Panel刷新,里面的Label文字改变为刷新的时间而外面的Label没有改变。

计时器控件在VB中的应用

计时器控件在VB中的应用 计时器控件在工具箱中的名称是Timer,该控件是一个非可视控件,即在运行时不可见,用于实现每隔一定时间间隔执行指定的操作。Timer控件对于其他后台处理也是非常有用的。本文用实例来介绍在VB程序中利用计时器控件,实现在程序在启动运行期间各种不同的效果。下面给出编程设计过程,供读者参考选用。 一、计时器(Timer)控件与标签(Label)控件的应用 1、启动VB,新建工程。在工程中添加一个窗体Form1,在窗体上加入一个Timer 计时器控件Timer1和标签控件Label1 2、编写相应的代码,实现不同的功能 (1)字体颜色发生随机变化的效果,计时器事件(Timer)代码如下: l 窗体Form1的加载事件代码 Private Sub Form_Load() Timer1.interval=500 Label1.Caption = “欢迎进入VB应用程序” Label1.font.size=20 Label1.autosize=true End Sub l 计时器(Timer1)控件的Timer事件代码 Private Sub Timer1_Timer() Label1.ForeColor = RGB(255 * Rnd, 255 * Rnd, 255 * Rnd) End Sub (2)依次出现字幕的实现效果,相关事件代码如下: Dim i …在通用-声明中定义变量… Private Sub Timer1_Timer() i = i + 1 Label1.Caption = Left(“欢迎进入VB应用程序”, i) If i > 10 Then i = 0 End If End Sub (3)滚动字幕的实现效果,相关事件代码如下: l 窗体Form1的加载事件代码 Private Sub Form_Load() Label1.Caption = “欢迎进入VB应用程序” End Sub l 计时器(Timer1)控件的Timer事件代码 Private Sub Timer1_Timer() If Label1.Left <= Form1.Width Then Label1.Left = Label1.Left + 100 Else Label1.Left = -Label1.Width End If End Sub (4)制作字体闪烁的效果

iFix定时器控件使用心得

iFix定时器控件使用心得 iFix的定时器控件,经常会把初学者搞得头晕脑涨,我说说自己的心得,供大家参考。 该控件是基于调度功能的,所以有一些用法和其它编程平台(如VB)里的定时器不太一样。 一、定时器的启动/停止 如果在编辑时TimerEnabled设为True,则运行时定时器会自动启动。如果在编辑时TimerEnabled设为False,则运行时需要先将TimerEnabled设为True,然后调用StartTimer方法。如果只将TimerEnabled设为True,但是不调用StartTimer 方法,定时器是不会开始工作的。如果要停止定时器,可以调用StopTimer方法,也可以直接将TimerEnabled设为False。也就是说有两种控制定时器启/停的方式: 方式一: 用如下代码启动:Timer1. TimerEnabled=True Timer1. StartTimer 用如下代码停止:Timer1. TimerEnabled=False 方式2: 在画面或调度的Initializes事件中加入:Timer1. TimerEnabled=True 用如下代码启动:Timer1. StartTimer 用如下代码停止:Timer1. StopTimer 二、以“连续”方式使用 以“连续”方式使用时,你会发现这样的现象,例如你希望一个画面被打开10秒钟后自动关闭,你会将定时器的Interval 属性设为10000,事实上却是,画面不到10秒就会被关闭,而且每次的延时时间还不是固定的,似乎是随机的,有时几乎是10秒,有时还不到1秒。这个举例中,定时器仅运行了1次(因为画面已经被关闭了),如果定时器一直运行下去,你还会发现,除了第一次的延时是“随机”的,从第二次开始,延时都是准确的。 这究竟是怎么回事呢?其实这是StartTime属性在起作用,StartTime属性的默认值是0:00:00,表示从午夜0点0分0秒开始,在这种情况下,如果设置为10秒钟的间隔,定时器被触发的时间将是每一分钟的0秒、10秒、20秒……50秒,如果从某一分钟的18秒启动了定时器,那么定时器第一次被触发的时间将会是20秒,也就是说,从启动到第一次触发之间仅有2秒钟的延时,如果你从15秒启动,会得到5秒钟的延时,这就是为什么你会觉得第一次的延时是“随机”的。 好的,既然知道了原因,自然也就有了解决的方法,那就是在每一次调用StartTimer方法之前,将StartTime属性设为当前时间,即Timer1. StartTime = Now就搞定了。例如在8:15:23秒启动,间隔10秒,第一次触发将会是在8:15:33秒的时候。 那是不是所有以“连续”方式使用时,这样作就都OK了呢?不是。这个方法是否有效(也就是得到精确的延时),要看你所希望的延时时间有多长,如果延时是10秒或更长,那没问题,这样是唯一正确且简便的方法。但如果你设置的延时间隔比较小,如3秒以内,甚至是毫秒级的,那么这个方法就会产生比较严重的误差。因为StartTime属性的时间精度只达到秒级,也就是说,实际的运行效果还是会有一定的误差,当然,这个误差最大不会超过1秒,所以一般来说对于5秒以上的延时设置,这个误差可以忽略。但如果延时设置是2秒,然后产生了接近1秒的误差,这就成问题了,误差率将近50%啊!如何解决此类问题呢?有办法,只是稍复杂一点。 例如,我们希望做到这样一个效果——有一个按钮对象(名为cmd1),当用鼠标点击这个按钮时,按钮消失不见,2秒钟之后又出现。也就是说在点击的时候把按钮的Visible属性设为False,并且启动一个定时器控件,2秒之后在定时器的OnTimeOut事件代码中,再把cmd1的Visible属性设为True。 如何比较精确地实现这2秒的时间间隔呢?具体做法是:将定时器的Interval属性设为100毫秒,定义一个模块级变

c_中timer控件的使用

C#中Timer组件用法 Timer组件是也是一个WinForm组件了,和其他的WinForm组件的最大区别 是:Timer组件是不可见的,而其他大部分的组件都是都是可见的,可以设计的。Timer组件也被封装在名称空间System.Windows.Forms中,其主要作用是当Timer组件启动后,每隔一个固定时间段,触发相同的事件。Timer组件在程序设计中是一个比较常用的组件,虽然属性、事件都很少,但在有些地方使用它会产生意想不到的效果。 其实要使得程序的窗体飘动起来,其实思路是比较简单的。首先是当加载窗体的时候,给窗体设定一个显示的初始位置。然后通过在窗体中定义的二个Timer组件,其中一个叫Timer1,其作用是控制窗体从左往右飘动(当然如果你愿意,你也可以改为从上往下飘动,或者其他的飘动方式。),另外一个Timer2是控制窗体从右往左飘动(同样你也可以改为其他飘动方式)。当然这二个Timer 组件不能同时启动,在本文的程序中,是先设定Timer1组件启动的,当此Timer1启动后,每隔0.01秒,都会在触发的事件中给窗体的左上角的横坐标都加上"1",这时我们看到的结果是窗体从左往右不断移动,当移动到一定的位置后,Timer1停止。Timer2启动,每隔0.01秒,在触发定义的事件中给窗体的左上角的横坐标都减去"1",这时我们看到的结果是窗体从右往左不断移动。当移动到一定位置后,Timer1启动,Timer2停止,如此反覆,这样窗体也就飘动起来了。要实现上述思路,必须解决好以下问题。 (1).如何设定窗体的初始位置: 设定窗体的初始位置,是在事件Form1_Load()中进行的。此事件是当窗体加载的时候触发的。Form有一个DesktopLocation属性,这个属性是设定窗体的左上角的二维位置。在程序中是通过Point结构变量来设定此属性的值,具体如下: //设定窗体起初飘动的位置,位置为屏幕的坐标的(0,240) private void Form1_Load ( object sender , System.EventArgs e ) { Point p = new Point ( 0 , 240 ) ; this.DesktopLocation = p ; } (2). 如何实现窗体从左往右飘动: 设定Timer1的Interval值为"10",就是当Timer1启动后,每隔0.01秒触发的事件是Timer1_Tick(),在这个事件中编写给窗体左上角的横坐标不断加"1"的代码,就可以了,具体如下:

使用C#的Timer控件来实现定时触发事件

使用C#的Timer控件来实现定时触发事件 C# Timer用法有哪些呢?我们在使用C# Timer时都会有自己的一些总结,那么这里向你介绍3种方法,希望对你了解和学习C# Timer使用的方法有所帮助。 关于C# Timer类在C#里关于定时器类就有3个 C# Timer使用的方法1.定义在System.Windows.Forms里 C# Timer使用的方法2.定义在System.Threading.Timer类里" C# Timer使用的方法3.定义在System.Timers.Timer类里 下面我们来具体看看这3种C# Timer用法的解释: ◆System.Windows.Forms.Timer 应用于WinForm中的,它是通过Windows消息机制实现的,类似于VB或Delphi中的Timer 控件,内部使用API SetTimer实现的。它的主要缺点是计时不精确,而且必须有消息循环,Console Application(控制台应用程序)无法使用。 ◆System.Timers.Timer 和System.Threading.Timer非常类似,它们是通过.NET Thread Pool实现的,轻量,计时精确,对应用程序、消息没有特别的要求。 ◆System.Timers.Timer还可以应用于WinForm,完全取代上面的Timer控件。它们的缺点是不支持直接的拖放,需要手工编码。 C# Timer用法实例 使用System.Timers.Timer类 System.Timers.Timer t = new System.Timers.Timer(10000); //实例化Timer类,设置间隔时间为10000毫秒; t.Elapsed += new System.Timers.ElapsedEventHandler(theout); //到达时间的时候执行事件; t.AutoReset = true; //设置是执行一次(false)还是一直执行(true); t.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件; public void theout( object source, System.Timers.ElapsedEventArgs e) { MessageBox.Show("OK!"); } C# Timer用法的基本情况就向你介绍到这里,希望对你了解和学习C# Timer使用有所帮助。详细参考:https://www.doczj.com/doc/2e186129.html,/zh-cn/library/vstudio/system.timers.timer.aspx

vb6.0时间控件timer详解

vb6.0时间控件timer详解 通过引发Timer 事件,Timer 控件可以有规律地隔一段时间执行一次代码。 语法 Timer 说明 Timer 控件用于背景进程中,它是不可见的 ************************以下是他的属性**************** Enabled 属性 返回或设置一个值,该值用来确定一个窗体或控件是否能够对用户产生的事件作出反应。 语法 object.Enabled [= boolean] Enabled 属性的语法包含下面部分: 部分描述 object 对象表达式,其值是“应用于”列表中的一个对象。如果object 被省略,则与活动窗体模块相联系的窗体被认为是object。 boolean 一个用来指定object 是否能够对用户产生的事件作出反应的布尔表达式。 设置 boolean 的设置为: 设置描述 True (缺省)允许object 对事件作出反应。 False 阻止object 对事件作出反应。 Enabled 属性示例 该例子使一个CommandButton 控件有效而不管TextBox 控件是否包含文本。要试用此例,先将下面的代码粘贴到带有CommandButton 和TextBox 控件的一个窗体的声明部分,然后按下F5 键并在文本框中随意输入一些内容。 Private Sub Form_Load () Text1.Text = "" ' 清除文本框的内容。

Command1.Caption = "Save" ' 在按钮上放置标题。 End Sub Private Sub Text1_Change () If Text1.Text = "" Then '查看文本框是否为空。 Command1.Enabled = False '使按钮无效。 Else Command1.Enabled = True '使按钮有效。 End If End Sub Interval 属性 返回或设置对Timer 控件的计时事件各调用间的毫秒数。 语法 object.Interval [= milliseconds] Interval 属性语法有以下组成部分: 部分描述 object 对象表达式,其值是“应用于”列表中的一个对象。 milliseconds 数值表达式,指定毫秒数,“设置值”中有详细说明,。 设置值 milliseconds 的设置值为: 设置值描述 0 (缺省值)使Timer 控件无效。 1 to 65,535 设置的时间间隔(以毫秒计),在Timer 控件Enabled 属性设置为True 时开始有效,例如,10,000 毫秒等于10 秒。最大值为65,535 毫秒,等于1 分钟多一些。 说明 可以在设计时或在运行时设置Timer 控件的Interval 属性。使用Interval 属性时,请记住: Timer 控件的Enabled 属性决定该控件是否对时间的推移做响应。将Enabled 设置为False 会关闭Timer 控件,设置为True 则打开它。当Timer 控件置为有效时,倒计时总是从其Interval 属性的设置值开始。 创建Timer 事件程序用以告诉Visual Basic 在每次Interval 到时该做什么。 Interval 属性示例

关于使用C#通过Timer控件实现自动播放图片的效果问题

关于使用C#通过Timer控件实现自动播放图片的效果问题 F1ake 4级被浏览52次 2013.04.23 using System; using System.Collections.Generic; using https://www.doczj.com/doc/2e186129.html,ponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace 第五章_work { public partial class Form1 : Form { public Form1() { InitializeComponent(); } int i = 0; private void picRight_Click(object sender, EventArgs e) { i--; if (i > -1) { picPicture.Image = ilImgList.Images[i]; } else { MessageBox.Show("已经是最后一张了","提示",MessageBoxButtons.OK,MessageBoxIcon.Excl amation); } } private void picLeft_Click(object sender, EventArgs e) { i++; if (i < 9)

{ picPicture.Image = ilImgList.Images[i]; } else { MessageBox.Show("已经是最后一张了", "提示", MessageBoxButtons.OK, MessageBoxIcon. Exclamation); } } private void Form1_Load(object sender, EventArgs e) { picPicture.Image = ilImgList.Images[0]; } private void picLook_Click(object sender, EventArgs e) { timer1.Enabled != timer1.Enabled; if (timer1.Enabled==true) { timer1.Start(); } else { timer1.Stop(); } } private void timer1_Tick(object sender, EventArgs e) { //if (count < ilImgList.Images.Count - 1) //{ // count++; //} //else //{

时钟控件

这一讲我们学习时钟控件的应用,应用程序运行如下左图所示,程序代码见下右图。 建立一个新的工程文件shili04.vbp。在窗体上放置一个文字标签Label1,设置Caption属性为“小雨点工作室VB初学者教程”;放置三个命令按钮Command1-3,Caption属性依次为“移动”、“停止”和“退出”。在工具箱 中找到时钟控件“”图标双击,在窗体上放置一个时钟控件Timer1。 时钟控件的主要属性只有两个:Enabled和Interval。 当Enabled设置为True时,应用程序会每间隔一定的时间触发一次Timer事件,就是执行一次 Private Sub Timer1_Timer() End Sub 之间的程序代码。而当Enabled设置为False时这一事件中止执行。 Interval属性决定了Timer事件循环执行的周期,单位为毫秒(1/1000秒)。 我们这个示例设置Enabled初始属性为False,Interval属性为50,程序运行时分析如下: 当单击Command1按钮时触发Command1的Click事件,程序执行 Private Sub Command1_Click() End Sub 之间的代码Timer1.Enabled = True,使时钟控件启动运行——字幕滚动开始。 当单击Command2按钮时触发Command2的Click事件,程序执行 Private Sub Command2_Click() End Sub 之间的代码Timer1.Enabled =False,使时钟控件中止运行——字幕滚动停止。 本事例我们使用了Timer控件的一个唯一事件Timer事件,当Timer的Enabled=True时,每间隔50毫秒时间程序会执行一次 Private Sub Timer1_Timer() End Sub 之间的代码 If Label1.Left < -2700 Then Label1.Left = 3150 Label1.Left = Label1.Left - 90 第一句代码的意思是:当标签Label1的左边距Left小于-2700时就让左边距值重新初始其值为3150。第二句代码的意思是:让标签Label1的左边距Left值在原有基础上减少90个单位。整个时钟控件的程序代码意思是:如果Time1的Enabled=True,那么每隔50毫秒时间间隔标签Label1的位置向左移动90个单位,但当标签L abel1移出窗体时让它的左边距重新初始位置。 大家可以试着改变Timer1的Interval的值,观察字幕滚动的快慢。

C#使用进度条ProgressBar和定时器Timer控件

C#使用进度条ProgressBar和定时器Timer控件 一、实例说明 ProgressBar类主耍用来显示进度,其Maximum和Minimum属性分别表示进度条的最大和最小值;Value属性则表示进度条当前的值,该值必须在Maximum 和Minimum属性设置的范围内;Step属性表示进度条的步进速度。 Timer类是一个定时器,可以控制定时触发某些事件,可以使用Enabled属性来控制是否激活定时器,使用Tick事件来实现定时器触发后实现的功能。 该实例通过ProgressBar类和Timer类来控制数字的显示,从100逐渐减少到O。 二、实现步骤 该实例的实现步骤如下: (1]新建市一个Windows项目,将该项目命名为“Progress_Sample”。 (2)添加控件。在新建立项目的表单中添加两个按钮button1和button2、一个文本编辑框textBoxl、一个进度条控件ProgressBar1、一个定时器控件timer1,其中,定时器控件是隐含控件。 (3)设置各个控件的属性。将textBoxl属性设置为100,将ProgressBar1的Maximum和Minimum属性分别设置为100和0,将其Step属性设置为10;将两个按钮的Text属性分别设置为“开始”和“退出”。并设置合适的字体。 (4)为两个按钮添加Click事件,为定时器添加Tick事件,并添加实现其功能的代码。 (s)运行程序并保存整个项目文件; 各控件写入代码如下: private void timer1_Tick(object sender, EventArgs e) { int i = 100; progressBar1.Value = progressBar1.Value + 1; i = 100-progressBar1.Value; textBox1.Text = i.ToString(); if (i == 0) { timer1.Enabled = false; } } private void button1_Click(object sender, EventArgs e) {

巧用vb的TIMER控件

Visual Basic提供一个Timer控件,其本质上是一个具有间隔时间设置所触发 的时间程序,使我们可以将其隐藏在系统中,以某一时间间隔触发相关程序。灵活地运用它可以取得很巧妙的效果。 下面,我们举一个例子。 我们可以在界面设计中设计出这样一种效果:一行文字在窗体中自左向右逐渐 滚动,从右边“滚”出窗体的文字,又在左边逐渐出现。如此循环下去。类似电视 上的滚动信息。这样可使你设计的软件显得很生动,极易引起用户的兴趣。其实,使用Visual Basic的Timer控件就可很容易地实现它。 首先,我们在窗体中设置两个Label控件Label1、Label2。这两个控件中除 Left属性外,其他属性设置成完全一样。这主要是为了实现循环滚动的效果。它们的Caption属性设置为要滚动显示的文字。另外再调整好其字体、大小和颜色等。在Form-Load过程中设置Label2.Left=-6240(窗体宽度),Label1.Left=0。这样可保证La bel1的一部分“滚”出窗体,则Label2的一部分就进入窗体。而形 成循环滚动在窗体中设置?/FONT>Timer控件。Timer控件的Interval属性决定滚动的速度,单位是毫秒。例如,我们设置成300,则每隔0.3秒滚动一次。然后,在Timer1-Timer()过程中加入如下程序: Private Sub Timer1-Timer() Label1.Left=Label1.Left+50 Label2.Left=Label2.Left+50 If Label1.Left>=6240 Then Label1.Left=-6240 End If

VB中的TIMER

VB中的timer VB高精度计时器编程的讨论 VB记时器编程的讨论在很多场合下编程(例如工业控制、游戏)中需要比较精确的记时器,本文讨论的是在VB下实现记时器的若干方法以及它们的精度控制问题。在VB中最常用的是Timer控件,它的设置和使用都非常方便,理论上它的记时精度可以达到1ms(毫秒)。但是众所周知的,实际上Timer在记时间隔小于50ms之下是精度是十分差的。它只适用于对于精度要求不太高的场合。这里作者要介绍的是两中利用Windows API函数实现精确记时的方法。第一中方法是利用高性能频率记数(作者本人的称呼)法。利用这种方法要使用两个API函数QueryPerformanceFrequency和QueryPerformanceCounter。QueryPerformanceFrequency 函数获得高性能频率记数器的震荡频率,该函数的定义如下: Private Declare Function QueryPerformanceFrequency Lib "kernel32" _ (lpFrequency As LARGE_INTEGER) As Long 函数中的数据结构LARGE_INTEGER定义如下: Type LARGE_INTEGER lowpart As Long highpart As Long End Type 调用该函数后,函数会将系统频率记数器的震荡频率保存到lpPerformanceCount中,其中低位保存到lowpart中,高位保存到highpart中。但是现在的Windows没有使用到hightpart (系统频率记数器的震荡频率与计算机的主频无关,我在几台机上做过验证,都是lowpart 为1193180,highpart为0)。 QueryPerformanceCounter函数获得系统频率记数器的震荡次数,函数的定义如下 Private Declare Function QueryPerformanceCounter Lib "kernel32" _ (lpPerformanceCount As LARGE_INTEGER) As Long 获得记时器震荡次数保存在lpPerformanceCount中。 显然,如果首先获得利用QueryPerformanceFrequency函数获得频率记数器的震荡频率,然后在执行某个程序段之前调用QueryPerformanceCounter函数获得频率记数器的震荡次数,在程序段结束再调用QueryPerformanceCounter函数获得频率记数器的震荡次数,将两次获得的震荡次数相减后再除以震荡频率就获得的了两次间隔之间的时间(以秒为单位)。如果在程序中建立一个循环,在循环中不停的调用QueryPerformanceCounter获得频率记数器的震荡次数并同先前的频率记数器的震荡次数相减,将结果除以频率记数器的震荡频率,如果达到一定的时间就执行某个任务,这样就实现了一个比较精确的记时器的功能。 另外的一种精确记时器的功能是利用多媒体记时器函数(这也是作者的定义,因为这个系列的函数是在Winmm.dll中定义并且是为媒体播放服务的)。 实现多媒体记时器首先要定义timeSetEvent函数,该函数的定义如下: Public Declare Function timeSetEvent Lib "winmm.dll" (ByVal uDelay As Long, ByVal _

visual-basic-程序设计--使用计时器控件(1)

visual basic 程序设计__使用计时器控件(1) 年级:高(二) 教学目标: 整体目标: 技能目标:掌握工具箱里的计时器控件的基本属性和事件,并会使用该控件编写简单的程序。 情感目标:激发学生学习VisualBasic程序设计的兴趣。 发展目标:培养独立思考、学习和创新精神,提高学生的信息素养。 层次目标: 基础簿弱学生的学习目标: 1.基本了解“计时器控件”的Enabled属性和Interval属性,会使用属性窗口进行相 关设置,初步学会用代码设置Enabled属性。 2.了解“计时器控件”的Timer事件何时被触发,并会编写简单程序的相应代码。[本 教案采用的程序是设计一个简单的“电子表”程序] 一般学生的学习目标: 1.熟练掌握“计时器控件”的Enabled属性和Interval属性,会使用属性窗口进行 相关设置,并会使用代码设置这些属性。 2.了解“计时器控件”的Timer事件何时被触发,熟练编写简单程序的相应代码, 并能根据帮助文件对“电子表”程序进行一定程度的扩充。[本教案采用的程序是 设计一个简单的“电子表”程序] 优等学生的学习目标: 1.熟练掌握“计时器控件”的Enabled属性和Interval属性,会使用属性窗口进行 相关设置,并会使用代码设置这些属性。 2.熟练掌握“计时器控件”的Timer事件何时被触发,熟练编写简单程序的相应代 码,并能根据帮助文件完善“电子表”程序。[本教案采用的程序是设计一个简单 的“电子表”程序] 教学重点: 1.了解如何在窗体上加入“计时器控件”即Timer控件,理解Timer控件的Enabled属 性、Interval属性和Timer事件。 2.学习使用Timer控件来编写“电子表”程序的关键子程序即Timer事件。 3.培养学生良好的程序设计结构和习惯。 教学难点:让学生发现程序的不足之处,并给出相应的解决方案。 教学过程 课前准备:按照课程要求,准备好要演示的程序,以及相应的帮助文件。 一、引入(1分钟) 1.上课后,将准备好的“电子表”程序演示给学生们看,激发学生的兴趣。 2.教师说话:如何来设计和实现一个简单的“电子表”程序呢,今天我们要来讲一个“计时器控件”,通过这个控件,我们就能设计和实现一个简单的“电子 表”程序了。 二、讲解(15分钟) 1.知识点介绍: (1)计时器控件像其它一般控件一样可在工具箱中找到。 (2)计时器控件是一个不可见控件,也就是说在设计阶段,你能够看到它,1文档来源为:从网络收集整理.word版本可编辑.

相关主题
文本预览
相关文档 最新文档