CStatic控件的基本使用
- 格式:docx
- 大小:19.56 KB
- 文档页数:13
一.数据源说到绘制图表,可能很多人的第一反应除了是图表呈现的方式外,更关心的便是数据如何添加,记得在很多年前,哪时要绘制一个数据曲线图,一直找不到好的呈现方式,后来使用了SVG的绘图模式,不过在添加数据的时候可谓吃尽了苦头,毕竟,SVG只是一种描述语言,要动态的实现一个图表的绘制,是非常困难的.对于微软的图表控件,数据添加是一件很简单的方式,它支持多种数据添加方式,如:·可以在图表的设计界面,在属性设置窗口中的Series属性下的Points中添加需要的数据.·可以在图表的设计界面中,在属性中绑定一个数据源.·可以在后台代码中,动态添加数据.·可以在后台代码中设置一个或多个数据源,直接绑定到图表中.在此处,我只着重讲解一下第3,4两点.对于第3点,相对来说比较简单,在后台代码中,找到要添加代码的Series,通过它下面Points的Add、AddXY、AddY等方法,即可以实现数据的添加.例如:1. double t;2. for(t = 0; t <= (2.5 * Math.PI); t += Math.PI/6)3. {4. double ch1 = Math.Sin(t);5. double ch2 = Math.Sin(t-Math.PI/2);6. Chart1.Series["Channel 1"].Points.AddXY(t, ch1);7. Chart1.Series["Channel 2"].Points.AddXY(t, ch2);8. }复制代码注:代码摘自微软的例子,上例中,Chart1为图表的名字,Channel 1、Channel 2分别表示两个Series数据序列)二.绑定数据先来看看图表控件都支持什么类型的数据绑定,根据官方文档的说法,只要是实现了IEnumerable接口的数据类型,都可以绑定到图表控件中,例如:DataView, DataReader, DataSet, DataRow, DataColumn, Array, List, SqlCommand, OleDbCommand, SqlDataAdapter, 及OleDbDataAdapter对象。
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 dataseries.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 collectionchart1.Series.Add(series);同时显示2条曲线// Populate series with random dataRandom 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 typeChart1.Series["Series1"].ChartType = SeriesChartType.Line; Chart1.Series["Series2"].ChartType = SeriesChartType.Spline;// Set point labelsChart1.Series["Series1"].IsValueShownAsLabel = true;Chart1.Series["Series2"].IsValueShownAsLabel = true;// Enable X axis marginChart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = true;// Enable 3D, and show data point marker linesChart1.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 attributesChart1.Series.Clear();Series series = new Series("FlowRead");series.ChartType = SeriesChartType.Column;series.BorderWidth = 3;series.ShadowOffset = 2;// Populate new series with dataseries.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 collectionChart1.Series.Add(series);很多点,效率还可以// Fill series datadouble 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 typeChart1.Series["Series1"].ChartType = SeriesChartType.FastLine;日期,xy类型// Create a new random number generatorRandom rnd = new Random();// Data points X value is using current date DateTime date = DateTime.Now.Date;// Add points to the stock chart seriesfor (int index = 0; index < 10; index++){Chart1.Series["Series1"].Points.AddXY( date, // X value is a daternd.Next(40,50)); //Close Y value// Add 1 day to our X valuedate = date.AddDays(1);int-int的xy数据绘图// Create a new random number generatorRandom rnd = new Random();// Add points to the stock chart seriesfor (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();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();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();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 sourceChart1.DataBind();conn.Close();数据库4,只绑定yChart1.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();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,绑定xyChart1.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();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();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,支持多lineChart1.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();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 databasestringfileNameString = this.MapPath(".");fileNameString += "..\\..\\..\\data\\chartdata.mdb";//Initialize a connectionstringstringmyConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileNameString;// Definethe databasequerystringmySelectQuery="SELECT * FROM SALESCOUNTS;";// Createa database connection object using the connectionstringOleDbConnection myConnection = newOleDbConnection(myConnectionString);// Create adatabase command on the connection usingqueryOleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);// Open theconnectionmyCommand.Connection.Open();//Initializes a new instance of the OleDbDataAdapter classOleDbDataAdapter myDataAdapter = new OleDbDataAdapter();myDataAdapter.SelectCommand = myCommand;//Initializes a new instance of the DataSet classDataSetmyDataSet = new DataSet();// Addsrows in the DataSetmyDataAdapter.Fill(myDataSet,"Query");foreach(DataRow row in myDataSet.Tables["Query"].Rows){// For each Row add a new seriesstring seriesName = row["SalesRep"].ToString();Chart1.Series.Add(seriesName);Chart1.Series[seriesName].ChartType = SeriesChartType.Line;Chart1.Series[seriesName].BorderWidth = 2;for(int colIndex = 1; colIndex <myDataSet.Tables["Query"].Columns.Count; colIndex++) {// For each column (column 1 and onward) add the value as apointstring 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 documentstringfileNameString = this.MapPath(".");stringfileNameSchema = this.MapPath(".");fileNameString += "..\\..\\..\\data\\data.xml";fileNameSchema += "..\\..\\..\\data\\data.xsd";//Initializes a new instance of the DataSet classDataSetcustDS = 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 classDataViewfirstView = 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 filestringfileNameString = 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 databasereaderOleDbDataReader myReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection);//Populate the chart with data in the fileChart1.DataBindTable(myReader, "HOUR");// closethe reader and the connectionmyReader.Close();myConnection.Close();使用csv数据// Filename of the CSV filestring file= "DataFile.csv";// Getthe path of the CSV filestring 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 queryOleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);// Openthe connection and create the readermyCommand.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 methodChart1.Series[0].Points.DataBindXY(myReader, "1", myReader,"2");// Closeconnection and data readermyReader.Close();myConnection.Close();数组绘图// Initialize an array of doublesdouble[] yval = { 2, 6, 4, 5, 3 };// Initialize an array of stringsstring[] xval = { "Peter", "Andrew", "Julie", "Mary", "Dave" };// Bind the double array to the Y axis points of the Default dataseriesChart1.Series["Series1"].Points.DataBindXY(xval, yval);数据库9,dataview// Resolve the address to the Access databasestringfileNameString = this.MapPath(".");fileNameString += "..\\..\\..\\data\\chartdata.mdb";//Initialize a connectionstringstringmyConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileNameString;// Definethe databasequerystringmySelectQuery="SELECT * FROM REPS;";// Createa database connection object using the connectionstringOleDbConnection myConnection = newOleDbConnection(myConnectionString);// Create adatabase command on the connection usingqueryOleDbCommandmyCommand = new OleDbCommand(mySelectQuery, myConnection);// Open theconnectionmyCommand.Connection.Open();//Initializes a new instance of the OleDbDataAdapter classOleDbDataAdapter custDA = new OleDbDataAdapter();custDA.SelectCommand = myCommand;//Initializes a new instance of the DataSet classDataSetcustDS = new DataSet();// Addsrows in the DataSetcustDA.Fill(custDS, "Customers");//Initializes a new instance of the DataView classDataViewfirstView = new DataView(custDS.Tables[0]);// Sincethe DataView implements IEnumerable, pass the dataview directlyinto// the DataBind method with thename of the Columns selected in thequeryChart1.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 generatorRandom rnd = new Random();// Add points to the stock chart seriesfor (int index = 0; index < 10; index++){Chart1.Series["Series1"].Points.AddXY(rnd.Next(10,90), // X value is a daternd.Next(40,50)); //Close Y value}Chart1.ChartAreas[0].AxisY.Minimum = 40;Chart1.ChartAreas[0].AxisY.Maximum = 50;数据排序// Use point index for drawing the chartChart1.Series["Series1"].IsXValueIndexed = true;// Sortseries points by second Y valueChart1.DataManipulator.Sort(PointSortOrder.Ascending, "Y2","Series1");查找数据最大值和最小值// Find point with maximum Y value and change colorDataPointmaxValuePoint =Chart1.Series["Series1"].Points.FindMaxValue(); maxValuePoint.Color = Color.FromArgb(255, 128, 128);// Findpoint with minimum Y value and change colorDataPointminValuePoint =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 chartSeriesseries = Chart1.Series.Add("My series");// Setseries and legend tooltipsseries.ToolTip = "#VALX: #VAL{C} million";series.LegendToolTip = "#PERCENT";series.PostBackValue = "#INDEX";series.LegendPostBackValue = "#INDEX";// Populateseries datadouble[] 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 attributesseries.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点击事件/// <summary>/// Page Load event handler./// </summary>protected void Page_Load(object sender, System.EventArgs e){this.Chart1.Click += new ImageMapEventHandler(Chart1_Click);// directusing of PostBackValueforeach(Series series in this.Chart1.Series){series.PostBackValue = "series:" + + ",#INDEX";}// transferof click coordinates. getCoordinates is a javascriptfunction.stringpostbackScript =ClientScript.GetPostBackEventReference(this.Chart1,"chart:@");this.Chart1.Attributes["onclick"] = postbackScript.Replace("@'", "'+ getCoordinates(event)"); }/// <summary>/// Handles the Click event of the Chart1 control./// </summary>/// <param name="sender">The sourceof the event.</param>/// <paramname="e">The<seecref="System.Web.UI.WebControls.ImageMapEventArgs"/>instance containing the eventdata.</param>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 pointHitTestResult 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();}}}}。
mfc中picture control使用在MFC中,Picture Control是一个用于显示图片的用户界面控件。
它通常用于在应用程序中展示图像内容。
以下是使用MFC中的Picture Control控件的步骤:1、添加Picture Control控件:在Visual Studio的设计视图中,打开你的对话框资源。
在工具箱中,找到Picture Control 控件并将其拖动到对话框上。
2、关联Picture Control控件与变量:选中Picture Control控件,在属性窗口中找到IDC_STATIC对应的ID,然后将其改为一个唯一的ID,比如IDC_PICTURE。
同时,在Class View中为该控件添加一个对应的变量,类型选择为CStatic。
3、加载并显示图片:在代码中找到对应的消息处理函数(例如OnInitDialog),然后使用以下代码加载并显示图片:cpp// 加载图片资源HRSRC hResource = FindResource(AfxGetResourceHandle(),MAKEINTRESOURCE(IDB_PICTURE), RT_RC);HGLOBAL hGlobal = LoadResource(AfxGetResourceHandle(), hResource);// 获取图片数据的指针LPCTSTR lpData = (LPCTSTR)LockResource(hGlobal);// 计算图片大小DWORD dwSize = SizeofResource(AfxGetResourceHandle(), hResource);// 创建位图对象CBitmap bitmap;bitmap.CreateFromBase(lpData, dwSize, NULL, LR_CREATEDIBSECTION);// 获取Picture Control控件的句柄HWND hWndPicture = GetDlgItem(IDC_PICTURE);// 创建兼容的DC(设备上下文)对象CDC compatibleDC;compatibleDC.CreateCompatibleDC(&compatibleDC);// 创建位图对象兼容的位图CBitmap* pOldBitmap = compatibleDC.SelectObject(&bitmap);// 将位图绘制到Picture Control控件上BitBlt(hWndPicture, 0, 0, bitmap.GetWidth(), bitmap.GetHeight(), &compatibleDC, 0, 0, SRCCOPY);// 释放资源compatibleDC.SelectObject(pOldBitmap);FreeResource(hGlobal);上述代码假设你的图片资源已经添加到资源文件中,并且资源的ID为IDB_PICTURE。
CStatic设置文字、字体、颜色和OnCtlColor的使用BOOL CreateFont( int nHeight, int nWidth, int nEscapement, int nOrientation, int nWeight, BYTE bItalic, BYTE bUnderline, BYTE cStrikeOut, BYTE nCharSet,BYTE nOutPrecision, BYTE nClipPrecision, BYTE nQuality, BYTE nPitchAndFamily, LPCTSTR lpszFacename );参数说明:nHeight :字体高度.>0:字体的高度值;=0:字体采用缺省直.<0:此值的绝对值为高度.nWidth :字体宽度.nEscapement :文本行的倾斜度.nOrientation :字符基线的倾斜度.nWeight:指定字体磅数(用每1000点中墨点像素数计)。
尽管nWeight 可为0到1000中的任意整数值,常用值和常数如下:以上各值是大约数,实际外观依赖字体大小,有的字体仅有FW_NORMAL,FW_REGULAR,FW_BOLD磅数。
如果FW_DONTCARE被指定,则使用缺省磅数。
bItalic :字体是否为斜体bUnderline :字体是否带下划线cStrikeOut :字体是否带删除线nCharSet :字体的字符集.ANSI_CHARSET.DEFAULT_CHARSET.SYMBOL_CHARSET.....nOutPrecision :字符的输出精度nClipPrecision :字符裁剪的精度nQuality :字符的输出质量nPitchAndFamily :字符间距和字体族(低位说明间距,高位说明字符族)lpszFacename :字体名称/v/mfcshouce/Class/CFont_CreateFont.htm设置字体BOOL CTMyDlg::OnInitDialog(){CDialog::OnInitDialog();//CFont m_Font;m_Font.CreateFont(-12,0,0,0,700,0,1,0,0,0,0,0,0,_T( "宋体 "));CEdit *m_Edit=(CEdit *)GetDlgItem(IDC_EDIT1);m_Edit->SetFont(&m_Font,FALSE);return TRUE; // return TRUE unless you set the focus to a control}小小说明:在OnInitDialog()中的//CFont m_Font;前的"//"号去掉,将类声明中的CFont m_Font;去掉会是什么结果?请自己试试.设置字体SetDlgItemText(IDC_STATIC1,"你好"); //设置文本设置颜色由于CStatic没有现成的接口,要么自己继承CStatic然后重写WM_CTLCOLOR的响应函数。
xtreme toolkit pro——CXTPReportControl控件教程作者:Kevin.Xiong来源:博客园发布时间:2011-03-31 14:10 阅读:31 次原文链接[收藏] CXTPReportControl控件是xtreme toolkit pro中的一个控件,它用来显示表格,可以显示表头表尾,可以对各列排序,拖放,等等,,也可以对各个单元格进行编辑,功能非常强大。
下面介绍一下他的使用:1. 在工程中头文件“stdafx.h”中添加:#include <XTToolkitPro.h> // Xtreme Toolkit Pro component library2. 如果要使用静态连接的方式,还应该:Add the following line to your application's .rc2 file. This will link in the toolkit resources so they are available to your application.#include <XTToolkitPro.rc>如果是动态连接的方式,需要xtreme toolkit的.dll拷贝到exe的输出目录下。
3. 添加CXTPReportControl控件:(1)在对话框中添加一个自定义控件,将该控件的class属性改为XTPReport,ID改为;IDC_REPORTCTRL_LIST。
(2)添加一个自定义变量:CXTPReportControl m_wndReportCtrl;(3)将控件和变量联系起来,在对话框初始化函数OnInitDialog()中添加如下代码:m_wndReportCtrlList.SubclassDlgItem(IDC_REPORTCTRL_LIST,this);4. 设置控件的外观://初始化报表的外观m_wndReportCtrl.AllowEdit(FALSE);//m_wndReportCtrl.EditOnClick(FALSE);//m_wndReportCtrl.EnableDragDrop(NULL, xtpReportAllowDrag | xtpReportAllowDrop);//允许拖曳行m_wndReportCtrl.EnableToolTips(TRUE);//在列头显示提示tooltips//m_wndReportCtrl.ShowHeader(TRUE);//显示头部(默认显示)//m_wndReportCtrl.ShowHeaderRows(TRUE);//显示头行//m_wndReportCtrl.ShowFooter(TRUE);//显示页脚footer,即界面下边,与header 对应//m_wndReportCtrl.ShowFooterRows(TRUE);//显示页脚行//m_wndReportCtrl.HeaderRowsAllowEdit(TRUE);//允许编辑HeaderRows//m_wndReportCtrl.FooterRowsAllowEdit(TRUE);//允许编辑FooterRows// COLORREF clrNew;// clrNew = RGB(0, 255, 0);// m_wndReportCtrl.SetGridColor(clrNew);//设置网格线颜色m_wndReportCtrl.SetGridStyle(TRUE,XTPReportGridStyle(xtpReportGridSolid) );//设置垂直网格线风格m_wndReportCtrl.SetGridStyle(FALSE,XTPReportGridStyle(xtpReportGridSolid ));//设置垂直网格线风格//m_wndReportCtrl.SetFreezeColumnsCount(2);//左侧两列冻住,注意,此方法必须在添加了列之后才能使用m_wndReportCtrl.GetPaintManager()->SetColumnStyle(XTPReportColumnStyl e(xtpReportColumnOffice2007));//设置列的风格//m_wndReportCtrl.GetPaintManager()->SetGridColor(clrNew);//设置网格线颜色m_wndReportCtrl.GetReportHeader()->AllowColumnRemove(FALSE);//不允许移除列m_wndReportCtrl.GetReportHeader()->AllowColumnResize(TRUE);//允许改变列的宽度m_wndReportCtrl.GetReportHeader()->AllowColumnSort(TRUE);//允许对列中的各行排序m_wndReportCtrl.GetReportHeader()->AllowColumnReorder(FALSE);//不允许列之间重新排序(通过拖拽列头部)m_wndReportCtrl.GetReportHeader()->SetAutoColumnSizing(TRUE);//不允许各列自动调节宽度//设置列宽自动调整为false,这样一来,所有列宽不是随reportControl的宽度变化而自动变化。
mfc cstatic getwindowtextw 使用方法-回复MFC CStatic GetWindowTextW 使用方法MFC(Microsoft Foundation Classes)是由Microsoft开发的一个C++类库,用于简化Windows应用程序的开发。
在MFC中,CStatic类代表一个静态文本控件,可以用于显示文本内容。
GetWindowTextW是CStatic类的一个成员函数,用于获取控件内的文本内容。
在本篇文章中,我们将一步一步回答关于MFC CStatic GetWindowTextW的使用方法。
首先,在MFC应用程序中创建一个CStatic控件,可以通过使用资源编辑器(Resource Editor)或者编程方式来完成。
资源编辑器是MFC中的一个工具,用于可视化地创建和编辑应用程序的资源,包括对话框和控件。
在资源编辑器中,可以添加一个CStatic控件并设置其中的属性,如控件ID、位置、大小和内容。
接下来,假设我们已经创建了一个名为m_staticText的CStatic控件。
要获取m_staticText控件的文本内容,需要调用GetWindowTextW函数。
GetWindowTextW函数是一个Windows API函数,用于获取一个窗口(Window)或控件(Control)的文本内容。
在MFC中,可以通过调用m_staticText的GetWindowTextW函数来获取文本内容。
GetWindowTextW函数有两个参数:第一个参数是一个指向缓冲区(Buffer)的指针,用于存储获取到的文本内容;第二个参数是缓冲区的大小。
在调用GetWindowTextW函数之前,需要先创建一个字符数组作为缓冲区,以存储获取到的文本内容。
以下是一个示例代码,演示了如何使用MFC CStatic GetWindowTextW 函数获取控件的文本内容:cpp声明一个字符数组作为缓冲区wchar_t szBuffer[256];调用GetWindowTextW函数获取文本内容m_staticText.GetWindowTextW(szBuffer, sizeof(szBuffer));在控制台输出获取到的文本内容wprintf(L"The text of m_staticText is: s\n", szBuffer);在上面的示例代码中,我们声明了一个大小为256的字符数组szBuffer 作为缓冲区。
MFC_基本控件使用MFC(Microsoft Foundation Classes)是一个用于基于 Windows 的应用程序开发的C++类库。
它提供了一套基本控件,使开发人员可以轻松地创建 Windows 应用程序的用户界面。
MFC提供了多种基本控件,用于显示和输入数据、与用户交互。
以下是一些最常见的基本控件及其用法:1. Button(按钮)控件Button 控件用于触发特定的操作或执行特定的功能。
创建 Button 控件的方法如下:```CButton myButton;myButton.Create("Click Me", WS_CHILD , WS_VISIBLE ,BS_PUSHBUTTON, CRect(10, 10, 100, 30), pParentWnd, ID_MYBUTTON);```其中,"Click Me" 是按钮的显示文本,WS_CHILD , WS_VISIBLE ,BS_PUSHBUTTON 是按钮的样式。
CRect(10, 10, 100, 30) 是按钮的大小和位置,pParentWnd 是按钮的父窗口,ID_MYBUTTON 是按钮的标识符。
Edit Control 控件用于接收用户输入的文本数据。
创建 Edit Control 控件的方法如下:```CEdit myEdit;myEdit.Create(WS_CHILD , WS_VISIBLE , WS_BORDER, CRect(10, 50, 300, 70), pParentWnd, ID_MYEDIT);```3. List Box(列表框)控件List Box 控件用于显示一个垂直列表,可以包含多个项。
创建 List Box 控件的方法如下:```CListBox myList;myList.Create(WS_CHILD , WS_VISIBLE , WS_BORDER ,LBS_NOTIFY, CRect(10, 90, 200, 200), pParentWnd, ID_MYLIST);```其中,WS_CHILD , WS_VISIBLE , WS_BORDER , LBS_NOTIFY 是列表框的样式。
介绍MSChart的常用属性和事件介绍MSChart的常用属性和事件MSChart的元素组成最常用的属性包括ChartAreas:增加多个绘图区域,每个绘图区域包含独立的图表组、数据源,用于多个图表类型在一个绘图区不兼容时。
AlignmentOrientation:图表区对齐方向,定义两个绘图区域间的对齐方式。
AlignmentStyle:图表区对齐类型,定义图表间用以对其的元素。
AlignWithChartArea:参照对齐的绘图区名称。
InnerPlotPosition:图表在绘图区内的位置属性。
Auto:是否自动对齐。
Height:图表在绘图区内的高度(百分比,取值在0-100)Width:图表在绘图区内的宽度(百分比,取值在0-100)X,Y:图表在绘图区内左上角坐标Position:绘图区位置属性,同InnerPlotPosition。
Name:绘图区名称。
Axis:坐标轴集合Title:坐标轴标题TitleAlignment:坐标轴标题对齐方式Interval:轴刻度间隔大小IntervalOffset:轴刻度偏移量大小MinorGrid:次要辅助线MinorTickMark:次要刻度线MajorGrid:主要辅助线MajorTickMark:主要刻度线DataSourceID:MSChart的数据源。
Legends:图例说明。
Palette:图表外观定义。
Series:最重要的属性,图表集合,就是最终看到的饼图、柱状图、线图、点图等构成的集合;可以将多种相互兼容的类型放在一个绘图区域内,形成复合图。
IsValueShownAsLabel:是否显示数据点标签,如果为true,在图表中显示每一个数据值Label:数据点标签文本LabelFormat:数据点标签文本格式LabelAngle:标签字体角度Name:图表名称Points:数据点集合XValueType:横坐标轴类型YValueType:纵坐标轴类型XValueMember:横坐标绑定的数据源(如果数据源为T able,则填写横坐标要显示的字段名称)YValueMembers:纵坐标绑定的数据源(如果数据源为Table,则填写纵坐标要显示的字段名称,纵坐标可以有两个)ChartArea:图表所属的绘图区域名称ChartType:图表类型(柱形、饼形、线形、点形等)Legend:图表使用的图例名称Titles:标题集合。
MFC常用控件使用MFC(Microsoft Foundation Classes)是一个用于Windows平台的C++类库,用于开发基于Windows的图形用户界面应用程序。
MFC提供了许多常用的控件,开发人员可以使用这些控件来构建各种类型的Windows应用程序。
下面是一些常用的MFC控件和它们的使用方法:1. Button控件:Button控件用于创建按钮。
创建Button控件的方法是通过调用CButton类的Create函数,指定按钮的风格、位置和大小等参数。
之后,可以使用CButton类的成员函数来设置按钮的文本、图片和事件处理程序等。
3. List Box控件:List Box控件用于创建列表框,用于显示列表项。
创建List Box控件的方法是通过调用CListBox类的Create函数,指定列表框的风格、位置和大小等参数。
之后,可以使用CListBox类的成员函数来添加、删除和获取列表项等。
5. Static控件:Static控件用于显示静态文本。
创建Static控件的方法是通过调用CStatic类的Create函数,指定静态文本的风格、位置和大小等参数。
之后,可以使用CStatic类的成员函数来设置静态文本的内容、字体和颜色等。
6. Slider控件:Slider控件用于创建滑动条。
创建Slider控件的方法是通过调用CSliderCtrl类的Create函数,指定滑动条的风格、位置和大小等参数。
之后,可以使用CSliderCtrl类的成员函数来设置滑动条的范围、当前位置和事件处理程序等。
7. Progress控件:Progress控件用于显示进度条。
创建Progress 控件的方法是通过调用CProgressCtrl类的Create函数,指定进度条的风格、位置和大小等参数。
之后,可以使用CProgressCtrl类的成员函数来设置进度条的范围、当前位置和事件处理程序等。
8. Tree Control控件:Tree Control控件用于显示树形结构。
CStatic控件的基本使用CStatic 继承于 CWnd,是一种特殊的窗体。
他可以显示文本字符串(这也是最常用的用法)、图标、指针(cursor)、位图和增强图文元件. 通常静态控件不提供输入和输出。
但是如果把他的属性设置为 SS_NOTIFY,他可以通知其父窗口的击鼠标事件。
如果文本不变,可以直接设置其 Caption。
如果想在运行过程中改变其显示文本,可以用如下方式:CStatic *pStatic=(CStatic*)GetDlgItem(IDC_STATIC);pStatic-SetWindowText("Just a Test of Static Control!");如果要显示图标,则必须要设置窗口属性为 SS_ICON 和 SS_CENTERIMAGE,实例代码CStatic* pStatic = (CStatic*)GetDlgItem(IDC_STATIC);LONG style = GetWindowLong(pStatic-GetSafeHwnd(), GWL_STYLE);style = SS_ICON;style = SS_CENTERIMAGE;SetWindowLong(pStatic-GetSafeHwnd(),GWL_STYLE,style);pStatic-SetIcon(m_hIcon);如果要显示 cursor,则必须要设置窗口属性为 SS_ICON 和 SS_CENTERIMAGE,实例代码CStatic* pStatic = (CStatic*)GetDlgItem(IDC_STATIC);LONG style = GetWindowLong(pStatic-GetSafeHwnd(), GWL_STYLE);style = SS_ICON;style = SS_CENTERIMAGE;SetWindowLong(pStatic-GetSafeHwnd(),GWL_STYLE,style);pStatic-SetCursor(OnQueryDragIcon());如果要显示图标,则必须要设置窗口属性为 SS_BITMAP 和 SS_CENTERIMAGE,实例代码//获得指向静态控件的指针CStatic *pStatic=(CStatic*)GetDlgItem(IDC_STATIC);//获得位图句柄HBITMAP hBitmap=::LoadBitmap(AfxGetApp()-m_hInstance,MAKEINTRESOURCE(IDB_BITMAP2));//LONG result = SetWindowLong(pStatic-GetSafeHwnd(),GWL_STYLE,style);//设置静态控件的样式,使其可以使用位图,并试位标显示使居中pStatic-ModifyStyle(0xF,SS_BITMAPSS_CENTERIMAGE);//设置静态控件显示位图pStatic-SetBitmap(hBitmap);使用Visual C++ 6.0编制软件时,静态控件是最常用的控件之一。
一般情况下,静态控件用作那些没有固定标题文本属性的控件(如文本控件、列表框等)的标签,或者用来为控件分组,或者用来显示一些提示性的文件。
实际上,静态控件除了显示静态文本这一基本功能外,还有许多其他的特殊功能,如在静态控件中可以显示图标、位图,甚至还可以在静态控件中显示动画。
本文将通过示例程序来介绍静态控件的这些特殊用法。
⑴ 使用AppWizard创建一个基于对话框的MFC应用程序,设置其工程名为ShowIco。
⑵ 在对话框上增加一个静态控件。
需要注意的是,有资源管理器添加的静态控件在默认情况下其ID均为IDC_STATIC,因此,如果需要在程序中区分和操纵各个不同的静态控件,一般情况下,需要更改新添加的静态控件的ID值。
这里将静态控件的ID值设置为IDC_SHOWICO。
⑶ 在资源管理器中添加图标资源,其ID为IDI_ICON1。
⑷ 使用ClassWizard添加WM_INITDIALOG消息处理函数OnInitDialog。
⑸ 在OnInitDialog函数中下面的代码://获得指向静态控件的指针CStatic *pStatic=(CStatic *)GetDlgItem(IDC_SHOWICO);//加载图标HICON hIcon=AfxGetApp()-LoadIcon(IDI_ICON1);//设置静态控件的样式,使其可以使用图标,并试图标显示使居中pStatic-ModifyStyle(0xF,SS_ICONSS_CENTERIMAGE);//设置静态控件图标pStatic-SetIcon(hIcon);运行该程序.⑴ 使用AppWizard创建一个基于对话框的MFC应用程序,设置其工程名为ShowBmp。
⑵ 在对话框上增加一个静态控件,将静态控件的ID值设置为IDC_SHOWBMP。
⑶ 在资源管理其中添加位图资源,其ID为IDB_INFO。
⑷ 使用ClassWizard添加WM_INITDIALOG消息处理函数OnInitDialog。
⑸ 在OnInitDialog函数中下面的代码://获得指向静态控件的指针CStatic *pStatic=(CStatic *)GetDlgItem(IDC_SHOWBMP);//获得位图句柄HBITMAP Bitmap=::LoadBitmap(AfxGetApp()_hInstance,MAKINTRESOURCE(IDB_INFO));//设置静态控件的样式,使其可以使用位图,并试位标显示使居中pStatic-ModifyStyle(0xF,SS_BITMAPSS_CENTERIMAGE);//设置静态控件显示位图pStatic-SetBitmap(hBitmap);运行该程序即可。
编写一个字符串在静态控件中不停的移动的程序。
⑴ 使用AppWizard创建一个基于对话框的MFC应用程序,设置其工程名为ShowAnimation。
⑵ 在对话框上增加一个静态控件。
将静态控件的ID值设置为IDC_PREVIEW。
⑶ 使用ClassWizard添加WM_INITDIALOG消息处理函数OnInitDialog和WM_TIMER 的消息处理函数OnTimer。
⑷ 在CshowAnimationDlg类中,增加两个变量m_x和m_y,用以表示字符串的坐标。
⑸ 在OnInitDialog函数中添加下列代码:m_x=0;m_y=0;KillTimer(1);VERIFY(SetTimer(1, 500, NULL) != 0);1.在CshowAnimationDlg类中,增加一个成员函数Draw() void CshowAnimationDlg::Draw(){CWnd *pWnd=GetDlgItem(IDC_PREVIEW);CDC *pDC=pWnd-GetDC();RECT rect;pWnd-GetClientRect(&rect);pWnd-Invalidate();pWnd-UpdateWindow();pDC-SelectStockObject(BLACK_BRUSH);pDC-Rectangle(0,0,rect.right,rect.bottom);pDC-SetTextColor(RGB(255,0,0));pDC-SetBkColor(RGB(0,0,0));if((m_x=rect.right)(m_y=rect.bottom-20)){ m_x=0;m_y=0;}pDC-TextOut(m_x,m_y,“"动画“");}2.在OnTimer函数中,添加如下代码:if (nIDEvent 1){m_x+=5;m_y+=5;Draw();}else CWnd::OnTimer(nIDEvent);MFC中 CStatic类(静态控件类)【说明】CStatic类提供了一个Windows静态控件的功能。
一个静态控件可以用来显示一个文本字符串、方框、矩形、图标、光标、位图或增强的图元文件。
它可以被用来作为标签、方框或用来分隔其它的控件。
静态控件通常不接收输入,也不提供输出;但是,如果它具有SS_NOTIFY风格,则它可以通知其父有关设备的消息。
创建一个静态控件分两步。
首先,调用构造函数来构造一个CStatic类的对象,然后调用成员函数Create来创建此静态控件并将它分配给当前的CStatic类的对象。
如果你是在一个对话框中创建了一个静态控件(通过一个对话框资源),则当用户关闭这个对话框时, CStatic类的对象被自动销毁。
如果你是在一个窗口中创建了一个CStatic类的对象,则可能需要你自己来销毁它。
在一个窗口的堆栈中创建的CStatic类的对象将自动被销毁。
如果你是使用new函数在堆中创建CStatic类的对象,则当你使用完后,必须调用delete来销毁这个CStatic类的对象。
【库名】afxwin.h【成员函数】(1)BOOL Create(LPCTSTR lpszText, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID = 0xffff);【返回值】如果本成员函数调用成功则返回非零值;否则返回0。
【参数】lpszText指定要放置在静态控件中的文本。
如果是NULL,则表示没有文本是可见的。
dwStyle指定静态控件的窗口风格。
以下任何静态控件风格的组合都可以用于这个控件。
SS_BITMAP指定在静态控件中显示一个被定义在资源文件中的位图。
该风格将忽略静态控件的高度和宽度,静态控件将根据位图的大小自动调节自身的尺寸。
SS_BLACKFRAME建立一个黑色的边框。
SS_BLACKRECT建立一个黑色的矩形。
SS_CENTER使文字在静态控件中水平居中。
SS_CENTERIMAGE当静态控件用于显示文本时,该风格将使文本在静态控件中垂直居中。
当静态控件用于显示位图或图标时,该风格将使位图或图标在静态控件中垂直居中,当位图或图标小于静态控件时,静态控件将使用位图或图标左上角的点的颜色填充空白处。
SS_ENHMETAFILE指定在静态控件中显示一个增强型图元文件。
该风格将不会忽略静态控件的高度和宽度,而图元文件将调节自身的大小来适应静态控件的尺寸。
SS_ETCHEDFRAME建立一个浮雕边框。
SS_ETCHEDHORZ建立一个边框,并将顶端边框设置为浮雕风格。
SS_ETCHEDVERT建立一个边框,并将左侧边框设置为浮雕风格。