delphi学习

来源:互联网 发布:echart动态获取数据 编辑:程序博客网 时间:2024/05/21 15:48

 1.[Error] DCansactionIformationManagement.pas(171): String literals may have at most 255 elements
[Fatal Error] DCMain.pas(32): Could not compile used unit 'DCansactionIformationManagement.pas'
报错:‘不正常定义了参数。提供了不一致或不完整信息’
解决方法:语法
数据定义要一致
2.Edit19.Text:= FieldbyName('SQTcost') 读取数据


  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, ComCtrls, TeeProcs, TeEngine, Chart, DbChart,
  ExtCtrls, Series

3.maskedit1.text:=datetostr(Date()); 获取当前日期
加一个timer控件,system里面有,是一块表的样子,呵呵。
双击进入ontimer事件,然后写下你的代码:
Statusbar1.Panels[0].Text:='系统日期:'+datetostr(Now);
Statusbar1.Panels[1].Text:='系统时间:'+timetostr(Now);

OPEN只用来SELECT
EXECSQL 用所有的
prepared告诉服务器准备要干活了

有返回一些记录的用OPEN
不需要返回记录的用EXECSQL
就是说一般用select 要用OPEN
而像insert .drop等只要用ExecSql

4.GetCursorValues(tmpX,tmpY);  { <-- get values under mouse cursor }
      Label1.Caption:=GetVertAxis.LabelValue(tmpY)+
                      ' '+
                      GetHorizAxis.LabelValue(tmpX);获取坐标值

5.滚动 代码  procedure TDemoForm.SpeedButton1Click(Sender: TObject);
begin
  HorizScroll(10);
end;

procedure TDemoForm.SpeedButton4Click(Sender: TObject);
begin
  HorizScroll(-10);
end;

procedure TDemoForm.SpeedButton2Click(Sender: TObject);
begin
  VertScroll(-10);
end;

procedure TDemoForm.SpeedButton3Click(Sender: TObject);
begin
  VertScroll(10);
end;


6.清除系列:if dbchart1.SeriesCount>=0 then
  begin
  for i:=0 to dbchart1.SeriesCount-1 do
    begin
      dbchart1.Series[i].Clear;
    end;
7.
  table2:=ttable.Create(self);
  table2.DatabaseName:='MS Access Database';
  table2.TableName:='趋势分析法';
  series1.DataSource:=table2;
  series1.XLabelsSource:='年份';

  series1.YValues.ValueSource:='预测用电量';
  Table2.open;
end;
8.

  if radiobutton1.Checked then
    try
    with DataModuleADO.ADOQuery1 do
     begin
      SQL.Clear;
      SQL.Add('insert into 回归分析法(年份,实际用电量,年国内生产总值,预测用电量,该年人口,误差,算法,备注)'+
                ' values (:年份,:实际用电量,:年国内生产总值,:预测用电量,:该年人口,:误差,:算法,:备注)');
      Parameters.ParamByName('年份').value := ComboBox1.text;
      Parameters.ParamByName('实际用电量').value := '';
      b:=StrToInt(Parameters.ParamByName('年国内生产总值').value );
      c:=StrToInt(Parameters.ParamByName('该年人口').value );
      Parameters.ParamByName('预测用电量').value :=-3.9848*b+0.0727+0.10307*c;
      Parameters.ParamByName('误差').value := '';
      Parameters.ParamByName('算法').value := '回归分析法';
      Parameters.ParamByName('备注').value := '';

      ExecSQL;
     end;
    Form22_DCfuheyuce_huiguifenxifa.show(Sender);

    except
    MessageDlg('计算出错',mtError,[mbok],0);
    end;
9;
1.整型
一个整型数据用来存放整数。Turbo Pascal支持五种预定义整型,它们是shortint(短整型)、 integer(整型)、 longint(长整型)、 byte(字节型)和 word(字类型),Turbo Pascal分别用相同的名字作为他们的表识符。每一种类型规定了相应的整数取值范围以及所占用的内存字节数。

类型数值范围占字节数格式

shortint-128..127 1 带符号8位

integer-32768..32767 2 带符号16位

longint-2147483648..2147483647 4 带符号32位

byte0..2551无符号8位word0..655352 无符号16位

说明:integer-32768..32767 2(占字节数) 带符号16位(格式)

Turbo Pascal规定了两个预定义整型常量表识符maxint和maxlongint,他们各表示确定的常数值,maxint为32767, maxlongint为2147483647,他们的类型分别是integer 和longint。

2.实型
一个实型数据用类存放实数。Turbo Pascal支持五种预定义实型,它们是real(基本实型)、 single(单精度实型)、double(双精度实型)、extended(扩展实型)、comp(装配实型),Turbo Pascal分别用相同的名字作为他们的标识符。每一种类型规定了相应的实数取值范围、所占用的内存字节数以及它们所能达到的精度。

类型数值范围占字节数有效位数

real2.9e-39..1.7e38 6 11..12

single1.5e-45..3.4e38 4 7..8

double5.0e-324..1.7e308 8 15..16

extended3.4e-4951..1.1e4932 10 19..20

comp-2**63+1..2**63-1 8 19..20

说明real2.9e-39..1.7e38 6(占字节数) 11..12(有效位数)

Turbo Pascal支持两种用于执行实型运算的代码生成模式:软件仿真模式和80x87浮点模式。除了real可以在软件仿真模式下直接运行以外,其他类型必须在80x87浮点模式下运行,要在程序头加编译指示{$N+,E+}

3.布尔型
一个布尔型数据用来存放逻辑值(布尔值)。布尔型的值只有两个:false和true,并且false的序号是0,true的序号是1。false 和true都是预定义常数标识符,分别表示逻辑假和逻辑真。boolean是布尔型的类型标识符。

4.字符型
字符型用char作为标识符。字符型必须用单引号括起来,字母作为字符型时,大小写是不等价的,并且字符型只允许单引号中有一个字符,否则就是字符串。

 

 

10.整数到字符串 IntTostr() 字符串=IntTostr(整数)
字符串到整数 strToInt()
字符串到小数 StrToFloat()
小数到字符串 FloatToStr()  修改库胡总的数据时候要数据类型~~~
11
    编写代码:
     procedure TForm1.Button1Click(Sender: TObject);
      begin
         edit1.Text:=IdIPWatch1.LocalIP;
       end;

  OK!按下F9功能键,运行程序,点击button看一下edit1中是不是已经显示了本机的IP

地址了?
12.
     平常使用软件的时候,经常听到一些程序居然有背景音乐.呵呵,边工作学习,边听音乐,真是一大乐趣!

  在delphi编程中如何实现播放背景音乐呢?我们都知道TMediaPlayer控件可以播放音乐,但我们现在不用它,我们用WINDOWS为我们提供的API函数来播放音乐,方法如下:

1 .首先需要在uses部分加入mmsystem.

2 .为播放按钮写代码:

MCISendString(OPEN e:/1.MID TYPE SEQUENCER ALIAS NN, , 0, 0);
MCISendString(PLAY NN FROM 0, , 0, 0);
MCISendString(CLOSE ANIMATION, , 0, 0);

3.为停止按钮写代码:

MCISendString(OPEN e:/1.MID TYPE SEQUENCER ALIAS NN, , 0, 0);
MCISendString(STOP NN, , 0, 0);
MCISendString(CLOSE ANIMATION, , 0, 0);

其中

NN为自定义名称标志,e:/1.mid为要播放的音乐文件.


13.
      本文主要讲解了如何控制数据库关键字的重复输入,这里我们举一个简单的例子来说明。为了方便我们就使用Delphi自带的数据库DBDEMOS,它是Paradox型的数据库,其中表employee.db具有关键字EmpNo。

     Table1的DataBaseName是DBDEMOS ,TableName是employee.db,Active设为True。DataSource1的DataSet是Table1。DBNavigator1和DBGrid1的DataSource是DataSource1。

     下面我们就要写Table的OnPostError事件:当出现重复的关键字时,首先要提示用户,然后取消此次操作。这个事件是在修改或向数据库插入记录时产生异常时才响应的。具体代码如下:

procedure TForm1.Table1PostError
(DataSet: TDataSet; E: EDatabaseError;
  var Action: TDataAction);
  begin
    if (E is EDBEngineError) then
if (E as EDBEngineError).Errors
[0].Errorcode = eKeyViol then
    begin
      MessageDlg('出现重复记录!',
 mtWarning, [mbOK], 0);
      Table1.Cancel;
      Abort;
    end;
end;

     说明:
     1. 通过EDBEngineError异常可以获得描述数据库驱动错误的详细信息。当EDBEngineError异常产生时,就会生成一个EDBEngineError对象,这个EDBEngineError对象包含有异常的错误信息,可以用程序进行分析,从而决定要完成的操作。

     2. 上面程序的Errorcode是BDE的错误代码,是一个word类型的变量,我们还需要定义它,定义如下

  const
  eKeyViol = 9729;
14.
  uses   Math;  
   
  Power(X,   Y);


15.
如何让数据块以不同颜色显示(除了TPieSeries是以不同颜色显示数据块外,其它的默认都是红色),并动态改变标题与页角及Y坐标的标题

 

--------------------------------------------------------------------------------

 

procedure TForm1.Button5Click(Sender: TObject);
begin
  Chart1.Series[0].ColorEachPoint:=True; //数据块不同色
  Chart1.LeftAxis.Title.Caption:='产品销售表';//Y坐标标题
  Chart1.Title.Text.Clear;
  Chart1.Title.Text.Add('哪个月份的销售记录');//图表标题
  Chart1.Foot.Text.Add('图表的说明文字'); //页脚内容
end;


1,Delphi中提供了大量的决策图表控件

Decision->决策,决断

Cube->立方体

Chart->图表

Series->系列

TeeChart->T型图表

Gallery->图库

Axis->轴线

Gradient->渐变

Legend->图例 传奇

 

--------------------------------------------------------------------------------

 

Delphi7中

TChart组件---------->Additional

TDBChart组件----------->Data Controls

Decision Cube组件组里有一整套

TVTChart->ActiveX

ChartFx->ActiveX


--------------------------------------------------------------------------------

 

图表(Chart)组件的属性绝大多数一样,用法也一样

1,去掉Chart的3D效果 View3D->False

2,标题文字 Title->Text 有字体属性

3,底部文字 Foot->Text 有字体属性

4,去掉轴线->AxisVisible->false

5,BottomAxis   RightAxis LeftAxis TopAxis->上下左右的坐标线

6,Frame->Mode->区域色与底色的模式

7,Frame->Style->边框样式

8,Gradient->渐变设置

9,很多属都可在双击Chart进行设置

10,MaxPointsPerPage->每页中容纳的最大数据量->如果为0则表示全部数据都装在一页中,当显示的数据较多时,要设这个属性,只有设了这个属性,才能把数据分页显示!

---------------------------------------------

设置这些就可以得到一个带渐变的Panel

------------------------------------------------------

如何动态增加一个图表?


--------------------------------------------------------------------------------

 

注意:TChart, TDBChart只是一个图表的容器控件,继承自Panel,而真正的图表是一个不可视的类

-----------------------------------------------------------------------------------------

定义条型(反映不同数据的变化情况,如,每月,每天销售的各大类情况,哪类销售最多,那类销售最少) 

var a:TBarSeries;

定义饼型(主要用于不同数据所占的比例,如销售中,各大类的销售情况)

var a:TPieSeries;

定义折线型(反映同一数据的变化,如每天,每月的销售变化, 这样可以看出,哪天,哪月的销售情况最好,最不好)

var a:TLineSeries

注意必须引用Series

 

--------------------------------------------------------------------------------

 

如何给一个图表赋值并显示在Chart中???

 

--------------------------------------------------------------------------------

 

procedure TForm1.Button2Click(Sender: TObject);
var
  a:TLineSeries;
begin
  a:=TLineSeries.Create(a);
  Chart1.AddSeries(a);
  a.AddArray([1,3,5,9,4,2])
end;

 

--------------------------------------------------------------------------------

 

如何在已显示出来的图表中增加数据?

 

--------------------------------------------------------------------------------

 

方法1

procedure TForm1.Button1Click(Sender: TObject);
begin
   Chart1.Series[0].AddXY(12,20,'新加的',clLime);

//12->X轴的坐标  20->Y轴的坐标  Clime是颜色
                                           
end;

 

--------------------------------------------------------------------------------

 

方法2

procedure TForm1.Button3Click(Sender: TObject);
begin
  Chart1.Series[0].Add(14,'打印机',clTeeColor);
  Chart1.Series[0].Add(18,'主板',clTeeColor);
  Chart1.Series[0].Add(23,'显示器',clTeeColor);

end;

 

--------------------------------------------------------------------------------

 

如何动态改变图表背景的渐变

 

--------------------------------------------------------------------------------

 

procedure TForm1.Button4Click(Sender: TObject);
begin
   Chart1.Gradient.Visible:=True;
   Chart1.Gradient.EndColor:=clTeal;
   Chart1.Gradient.StartColor:=clWhite;
end;

 

--------------------------------------------------------------------------------

 

如何让数据块以不同颜色显示(除了TPieSeries是以不同颜色显示数据块外,其它的默认都是红色),并动态改变标题与页角及Y坐标的标题

 

--------------------------------------------------------------------------------

 

procedure TForm1.Button5Click(Sender: TObject);
begin
  Chart1.Series[0].ColorEachPoint:=True; //数据块不同色
  Chart1.LeftAxis.Title.Caption:='产品销售表';//Y坐标标题
  Chart1.Title.Text.Clear;
  Chart1.Title.Text.Add('哪个月份的销售记录');//图表标题
  Chart1.Foot.Text.Add('图表的说明文字'); //页脚内容
end;

 


17;自由改变图形
  var      
      bar:   TbarSeries;  
      pie:   TpieSeries;  
  begin  
  //柱形图    
      Title.Text.Clear;  
        Title.Text.Add('表名称');                          
        bar   :=   TbarSeries.Create(nil);  
        bar.Clear;  
        bar.ParentChart   :=   DBChart1;    
        bar.add(123,'name');  
  //饼图  
      if   DBchart1.SeriesCount   >   0   then  
          DBchart1.Series[0].Free;//如果表中有图型将先FREE  
       
        Title.Text.Clear;  
        Title.Text.Add('表名称');                          
        pie   :=   TbarSeries.Create(nil);  
        pie.Clear;  
        pie.ParentChart   :=   DBChart1;    
        pie.add(123,'name');  
   
   
  end;

18:
    if DBchart1.SeriesCount>0   then
   DBchart1.Series[0].Free;
  清楚图表
19 ;
   窗体的基本方法
(1)Close方法
     该方法的执行将关闭窗体,其基本语法为:Form1.Close;
(2)Hide方法
    
该方法将窗体隐藏起来,其基本语法为:Form1.Hide;
(3)Release方法
   
 该方法将关闭窗体并释放窗体及窗体中组件所占用的内存。
(4)Show方法
   

 该方法将显示窗体或将窗体置前,使用Show方法可以在窗体不关闭的情况下切换到调用它的窗体。值得注意的是:
在调用其它窗体时,首先要将被调用窗体的单元引用到调用单元中。
(5)ShowModal方法
     该方法将显示一个模式窗体(
即不能够切换到其它窗体,如需切换必须关闭这个窗体)。
20,
 7)TabOrder属性
     TabOrder属性用来指定按Tab键时获得焦点的顺序。TabOrder属性的取值类型为Integer,从0开始。
TabOrder属性的设置适用于所有能够获得焦点的组件,可以在组件上单击鼠标右键,在弹出菜单上选择“Tab键顺序…”来设置Tab键顺序

21,Label组件的常用事件:
(1)OnMouseEnter事件
    
当鼠标移动到标签上时触发该事件。
(2)OnMouseLeave事件
   
 当鼠标离开标签时触发该事件。22
Active属性用来说明数据库文件的打开状态。应用Active属性来决定及设定一个数据集组件与


数据库数据之间的关系。当Active属性值为True时,表明数据集是打开的,数据集组件可以对

数据库进行读写操作,否则表示数据集是关闭的,数据集组件不能从数据库读取数据,也不能
向数据库中写数据。应用程序在改变其它影响数据库状态或在应用程序中显示数据的组件状态
的属性之前,必须先将Active属性设置为False。
23
 Query1.Fields[0].DisplayLabel:=’第一列’
使用方法FieldByName按照字段的名字来访问,如显示studentinfo表中Name属性值只需要使
用代码Edit1.text:=Table1.FieldByName(‘Name’).AsString;
24
 try…except…end
25
  i : integer;
  begin
    for i :=0 to ListView1.Items.Count-1 do
    if ListView1.Items[i].Selected then
       begin
     if ListView1.Items[i].SubItems.Strings[7]='2' then
        begin
        a:=ListView1.Items[i].Caption;
        b:=ListView1.Items[i].SubItems.Strings[0]; //行 列
26
  DataModule3.adoquery1.close;   
            DataModule3.adoquery1.SQL.clear;
            DataModule3.adoquery1.SQL.add ('select  密码   from  login where 用户名='''+s+''' ');
            DataModule3.adoquery1.Open;
            m:=DataModule3.adoquery1.FieldByName('密码').Asstring;
            DataModule3.adoquery2.close;
            DataModule3.adoquery2.SQL.clear;
            DataModule3.adoquery2.SQL.add ('select  类别 from  login where 用户名='''+s+''' ');
            DataModule3.adoquery2.Open;
            n:=DataModule3.adoquery2.FieldByName('类别').Asstring;
27
 const
TVS_CHECKBOXES = $00000100;

procedure SetComCtrlStyle(WinCtrl: TWinControl; Value: Integer; UseStyle: Boolean);
var
Style: Integer;
begin
  if WinCtrl.HandleAllocated then
  begin
    Style := GetWindowLong(WinCtrl.Handle, GWL_STYLE);
    if not UseStyle then
    Style := Style and not Value
    else Style := Style or Value;
    SetWindowLong(WinCtrl.Handle, GWL_STYLE, Style);
  end;
end;

 


然后 在 OnCreate 调用:


SetComCtrlStyle(TreeView1, TVS_CHECKBOXES, True);
 

 

或者干脆简单点,一句话完事:


SetWindowLong(TreeView1.Handle, GWL_STYLE, GetWindowLong(TreeView1.Handle, GWL_STYLE) or $00000100);
 
28
   for i:=dbChart1.SeriesCount-1 downto 0 do
         begin
         dbChart1.Series[i].Free;
29
rocedure TFrmBmGzxmTj.Button1Click(Sender: TObject);
var
  i:integer;
  xls :OleVariant;
begin
  if ((DM_GSGL.QryGzxmTj.active=false) or (DM_GSGL.QryGzxmTj.RecordCount=0)) then
  begin
    MessageDlg('没有数据,输出失败!',mtError, [mbYes],0);
    Exit;
  end;
  xls:=CreateOleObject('Excel.Application');
  xls.WorkBooks.add;
  xls.Visible:=true;
  xls.cells(1,2):='从'+FormatDateTime('yyyymmdd',DtpDate1.Date)+'到'+FormatDateTime('yyyymmdd',DtpDate2.Date);
  xls.cells(2,1):='工号';
  xls.cells(2,2):='姓名';
  xls.cells(2,3):='人员类别';
  xls.cells(2,4):='总工时';
  i:=3;
  with DM_GSGL.QryGzxmTj do
  begin
    First;
    while not Eof do
    begin
      xls.cells(i,1):=Fieldbyname('工号').asstring;
      xls.cells(i,2):=Fieldbyname('姓名').asstring;
      xls.cells(i,3):=Fieldbyname('人员类别').asstring;
      xls.cells(i,4):=Fieldbyname('总工时').asstring;
      i:=i+1;
      Next;
    end;
  end;
  i:=i+1;
  xls.cells(i,1):='工时合计';
  xls.cells(i,4):=label4.Caption;
end;
30
 procedure TForm1.Button1Click(Sender: TObject);
begin
  Chart1.Series[0].AddXY(12,20,'新加的',clLime);

//12->X轴的坐标 20->Y轴的坐标 Clime是颜色
  
end;


 

方法2

procedure TForm1.Button3Click(Sender: TObject);
begin
  Chart1.Series[0].Add(14,'打印机',clTeeColor);
  Chart1.Series[0].Add(18,'主板',clTeeColor);
  Chart1.Series[0].Add(23,'显示器',clTeeColor);

end;


 

如何动态改变图表背景的渐变


 

procedure TForm1.Button4Click(Sender: TObject);
begin
  Chart1.Gradient.Visible:=True;
  Chart1.Gradient.EndColor:=clTeal;
  Chart1.Gradient.StartColor:=clWhite;
end;


 

如何让数据块以不同颜色显示(除了TPieSeries是以不同颜色显示数据块外,其它的默认都是红色),并动态改变标题与页角及Y坐标的标题


 

procedure TForm1.Button5Click(Sender: TObject);
begin
  Chart1.Series[0].ColorEachPoint:=True; //数据块不同色
  Chart1.LeftAxis.Title.Caption:='产品销售表';//Y坐标标题
  Chart1.Title.Text.Clear;
  Chart1.Title.Text.Add('哪个月份的销售记录');//图表标题
  Chart1.Foot.Text.Add('图表的说明文字'); //页脚内容
end;

 

效果如下:

 

 


 

数据太多了,想翻页显示怎么做?


 

1,设置Chart->MaxPointsPerPage(每页的最大数据量)->只有设置了这个置才可能分页,如果是0表示,全部数据都在一页上

2,可以使用点击左右坐标进行上下翻页也可以点击鼠标的左右键进行翻页
-----------------
procedure TForm1.Chart1ClickBackground(Sender: TCustomChart;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if Button=mbLeft then Chart1.NextPage;
  if Button=mbRight then Chart1.PreviousPage;
end;

 

如何标显特殊数据(当点特殊数据时以不同颜色进行显示)


 

procedure TForm1.Chart1ClickSeries(Sender: TCustomChart;
  Series: TChartSeries; ValueIndex: Integer; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  Series.ValueColor[ValueIndex]:=clRed;
end;

 

动态图表分析技术


 

DBChart

-------------------------------

动态图表的连接方式分2种

①手工方式连接数据库

②运用DBChart属性,在动行时动态连接数据库

---------------------------------------

1,DBChart对于数据是只图的,所以他连接数据库表,关不是直接挂连ACCESS组件,而是直接连接DataSet,Table,Query,ClientDataSet这样的数据集组件

2,首先要设好数据据组件的连接,再设置DBChart与数据组件连接

方法如下:

①双击DBChart->Series->设置标题,X的数据,Y(Bar)的数据

 

②,如果是在动行时设置是设置是设置DBChart的如下属性

DBChart->DataSet

DBChart->XLabelSource

DBChart->XValues

DBChart->YValues

----------------------------

procedure TForm1.Button3Click(Sender: TObject);
begin
  DBChart1.Series[0].DataSource:=ADODataSet1;
  DBChart1.Series[0].XLabelsSource:='酒水名称';
  DBChart1.Series[0].XValues.ValueSource:='单价';//写的都是字段名称
  DBChart1.Series[0].YValues.ValueSource:='单价';
end;

----------------------------------------

 

如何让DBChart自动更新数据显示

 

1,手动更新需设置DBChart->AutoRefresh->Rrue或False

2,自动更新设置DBChart->RefreshInterval的值,以秒为单位,每隔多少秒更新一次数据
30 listbox的用法
 var
  i:Integer;
begin
  for i :=0 to ListBox1.Count-1 do
  begin
    if ListBox1.Selected[i] then
    ListBox2.Items.Add(ListBox1.Items.Strings[i]);
  end;
  ListBox1.DeleteSelected;//增加后删除所选的记录
end;
31
 delphi listbox 添加数据
 悬赏分:10 - 解决时间:2009-2-25 16:23
怎么把 数据库 当中的某一列stu_id数据全部添加到listbox当中啊
var s:string;
 close;
 sql.Clear;
 sql.Add('select stu_id  from students');
 s:=fieldbyname('nnbianhao').AsString;
 open;
 first;
 while not EOF  do
 begin
 ListBox1.Items.Add(s);
 next;
 end ;
32
 Chart.Free;  
 Series.Free;
33 dbchart的使用
ADOQuery1.Active:=True;
DBChart1.Series[0].DataSource:=ADOQuery1;
DBChart1.Series[0].XLabelSource:='FiledName';
DBChart1.Series[0].YValues.ValueSource:='FieldName';

2.切换图表类型
tmpChart:=DBChart1.Series[0];
ChangeSeriesType(tmp,TLineSeries);
tmpChart.Active:=True;
tmpChart.RefreshSeries;

3.设置分页
DBChart1.ScaleLastPage:=true;
DBChart1.MaxPointsPerPage:=10;


DBChart1.Page:=1; 代码实现
DBChart1.PreviousPage;
DBChart1.NextPage;
DBChart1.Page:=NumPages;

4.导出图表
SaveToBitmapFile(FileName);

5.打印图表
uses TeePrevi;
ChartPreview(Parent,DBChart1);
TeePreview(Parent,DBChart1);

6.数据源
ADODataSet1.CreateDataSet;
AdoDataSet1.Insert;
AdoDataSet1.FieldByName('Value').AsFloat:=200000;
AdoDataSet1.FieldByName('Info').AsString:='05-02';
AdoDataSet1.Post;  

33
  ado:
 ADOConnection1.GetTableNames
  for i:= 0 to ADOQuery1.FieldCount-1
       adoQuery1.Fields[i].FullName;
....

bde:
34
 桂A-捞佬(371775431) 11:27:07
怎样在stringgrid中导入Excel
川A-小鲤鱼(252966040) 11:29:09
用个读写EXCEL的控件
川A-小鲤鱼(252966040) 11:29:27
读出EXCEL的CELL值,并加入StringGrid中就行了
35》
  formatdatetime('aaa',now);//当前星期  
  formatdatetime('c',now);//以2003-8-16   23:03:23的形式显示当前日期和时间  
  formatdatetime('d',now);//显示当前的日期   1被显示成1  
  formatdatetime('dd',now);//显示当前的日期   1被显示成01  
  formatdatetime('ddd',now);//显示当前的星期  
  formatdatetime('ddddd',now);//以2003-8-1的形式显示年月日  
  formatdatetime('dddddd',now);//以2003年8月1日的形式显示年月日  
  formatdatetime('dddddd   ddd',now);//以‘2003年8月1日   星期五’的形式显示年月日及星期  
  formatdatetime('e',now);//显示年的最后一位2003被显示成3  
  formatdatetime('ee',now);//显示年的最后二位2003被显示成03  
  formatdatetime('eee',now);//显示年2003被显示成2003  
  formatdatetime('h',now);//显示小时1被显示成1  
  formatdatetime('hh',now);//显示小时1被显示成01  
  formatdatetime('m',now);//显示月1被显示成1  
  formatdatetime('mm',now);//显示月1被显示成01  
  formatdatetime('mmm',now);//以‘八月’的形式显示月份  
  formatdatetime('n',now);//显示当前分钟1被显示成1  
  formatdatetime('nn',now);//显示当前分钟1被显示成01  
  formatdatetime('s',now);//显示当前秒1被显示成1  
  formatdatetime('ss',now);//显示当前秒1被显示成01  
  formatdatetime('t',now);//以1:05的形式显示小时和分钟  
  formatdatetime('tt',now);//以1:06:13的形式显示小时和分钟和秒  
  formatdatetime('y',now);////显示年的最后二位2003被显示成03  
  formatdatetime('yyy',now);//显示年2003被显示成2003  
  formatdatetime('z',now);//显示当前毫秒1被显示成1  
  formatdatetime('zz',now);//显示当前毫秒1被显示成01  
  formatdatetime('zzz',now);//显示当前毫秒1被显示成001


         while not DataModuleADO.ADOQuery1.eof do
    begin
    for i:=0 to DataModuleADO.ADOQuery1.DataSet.Field.Count-1 do
    begin
    a                      Single
    end;

  Next;

  begin
          SetLength(strlist,DBGrid1.DataSource.DataSet.FieldCount-1);
          for   j:=0  to  DBGrid1.DataSource.DataSet.FieldCount-1   do
          strlist[j]:=DBGrid1.DataSource.DataSet.Fields[j].AsString;
         end;


本实例要在窗体上直接绘制正弦曲线,为了防止窗口切换的过程中会输出不完整的图形,因此绘制图形的关键代码都放在了窗体的OnPaint过程中,代码如下:
procedure TForm1.FormPaint(Sender: TObject);
var
 x: Integer;
 y,a: Double;
begin
 Canvas.Pen.Width:=3;
 Canvas.MoveTo(0,Trunc(self.ClientHeight/2));
 for x := 0 to self.ClientWidth do
 begin
  a := (x/self.ClientWidth) * 2 * Pi;
  y := Sin(a);
  y := (1-y)*self.ClientHeight/2;
  Canvas.LineTo(Trunc(x), Trunc(y));
 end;
end;
  程序首先设置了窗体的Canvas对象中画笔的宽度,并且把绘图的起点移动到了窗体中(0,Trunc(self.ClientHeight/2))的位置。然后通过一个循环中的a:= (x/self.ClientWidth)*2*Pi语句将一个正弦周期内的角度值转换为弧度值,并且把正弦计算后的结果存储在变量y中。最后,循环中的Canvas.LineTo(Trunc(x), Trunc(y))语句就会在窗体上绘制出连续的正弦曲线。
  程序代码如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
 TForm1 = class(TForm)
 procedure FormPaint(Sender: TObject);
 procedure FormResize(Sender: TObject);
 procedure FormCreate(Sender: TObject);
private
 { Private declarations }
public
 { Public declarations }
end;
var
 Form1: TForm1;
 implementation
 {$R *.dfm}
 procedure TForm1.FormPaint(Sender: TObject);
var
 x: Integer;
 y,a: Double;
begin
 Canvas.Pen.Width:=3;
 Canvas.MoveTo(0,Trunc(self.ClientHeight/2));
 for x := 0 to self.ClientWidth do
 begin
  a := (x/self.ClientWidth) * 2 * Pi;
  y := Sin(a);
  y := (1-y)*self.ClientHeight/2;
  Canvas.LineTo(Trunc(x), Trunc(y));
 end;
end;
procedure TForm1.FormResize(Sender: TObject);
 begin
  Refresh;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
 self.DoubleBuffered:=true;
 //防止图形闪烁
end;
end.
  保存文件,然后按F9键运行程序。在程序运行过程中,会自动在窗体上绘制正弦曲线,运行结果如图1所示。

图1 程序运行结果

  通过本程序的学习,不但可以绘制正弦曲线,也可以绘制余弦曲线、正切曲线等各式各样的曲线,方便科学研

 

 

 


基本安装1、对于单个控件,Componet-->install component..-->PAS或DCU文件-->install;2、对于带*.dpk文件的控件包,File-->Open(下拉列表框中选*.dpk)-->install即可;3、对于带*.bpl文件的控件包,Install Packages-->Add-->bpl文件名即可;4、如果以上Install按钮为失效的话,试试Compile按钮;5、是run time lib则在option下的packages下的runtimepackes加之。    如果编译时提示文件找不到的话,一般是控件的安装目录不在Delphi的Lib目录中,有两种方法可以解决:1、反安装的源文件拷入到Delphi的Lib目录下;2、或者Tools-->Environment Options中把控件源代码路径加入到Delphi的Lib目录中即可。注意:所安装的控件是否与你所用的Delphi版本相适应。
 控件删除在Component/Install Packages中删除。 选Component/configure Palette…有pages和components两个区域双击components区域,选中要删除得控件,下面有得Delete按钮但系统提供的控件只能Hide,不能delete。打开控件所在的包文件(*.dpk),从中删除控件那个文件,再重新编译该包即可如果是整个控件包都要删除的话,project->Option->Packages,删掉那个packages,ok~

 

   ARP -s -d-a
  
   -s——将相应的IP地址与物理地址的捆绑。
  
   -d——删除所给出的IP地址与物理地址的捆绑。
  
   -a——通过查询Arp协议表来显示IP地址和对应物理地址情况。

 

、怎么样在delphi中调动其它*.exe文件?
例如:winexec('d:/郑洽/Project1.exe',sw_show);

==============================================================================

2、如何让工程运行时主窗体就是最大化的?
答:设置主窗体的WindowsState属性为wsMaximized就可以了!
wsNormal 窗体以普通状态显示
wsMinimized 窗体以最小化状态显示。
wsMaximized 窗体以最大化状态显示。

==============================================================================

3、我想先->闪现窗体->主窗体->登录窗体,工程源文件怎么设置?
答:
⒈开始一个新工程。给表格起名为MainForm,MainForm的单元起名为Main, 工程文 件起名为Test。
⒉在MainForm中插入一个Button部件,将其Caption属性设为“关闭”,为该部件 的onClick事件创建一个过程,并在过程的begin和end之间插入Close语句。
⒊在应用程序添加一个表格,将这个表格起名为MoveForm,MoveForm 的单元起名 为Move。
⒋为便于演示,在MoveForm中插入一个Label部件,设置其Caption 属性为“欢迎 进入本系统”。
5.下一步修改工程的源代码。选择View/Project Source,修改begin和end之间的 语句如下:
程序清单Test.Dpr
program Test
uses
forms,
Main in 'MAIN.PAS'{MainForm},
Move in 'Move.PAS'{MoveForm}

{$R *.RES}

begin
MoveForm:=TMoveForm.Create(Application);{Create创建闪现窗口对象}
MoveForm.Show;
MoveForm.Update;
Application.CreateForm(TMainForm,MainForm);
MoveForm.Hide;
MoveForm.Free;{Free从内存中释放对象}
Application.Run;
end.
  第一条语句创建了对象,该对象存在内存中,但还不能看见, 为了让它出现并更 新它的内容,调用对象的Show和Update成员函数:Show和Update。 当闪现窗口使 用完后,用Hide函数将它隐藏起来,然后用Free函数释放它所占据的内存。
6.如果此刻你编译和运行程序,MoveForm窗口一闪而过, 你可能未来得及看 清。为使MoveForm窗口显示几秒种,我们可为MainForm的OnCreate 事件创建一个 处理程序,延迟MoveForm窗口的显现时间。
program TMainForm.FormCreate(sender:Tobject);
var
currentTime:LongInt;
begin
currentTime:=GetTickCount div 1000;
while ((GetTickCount div 1000)<(currentTime+3) do
{不做任何事);
end;
end.
  GetTickCount函数返回窗口启动后过去的毫秒数,这个值除以1000 转化为秒数。 此时你编译运行程序,就能得到一个延迟3秒多的闪现窗口。
为闪现窗口添加上Image部件,再对字体及窗口进行修饰,我们就能为应用程 序,创建一个精美的封面或在程序启动时显示重要提示。

制作登录窗体一个很方便的方法就是主窗体作为主窗体,登录成功Hide掉就行了。
如果登录窗体不可以作为主窗体,那么和闪现窗体一样的方法创建登录窗体,加在Application.Run;之前,MoveForm.Free;之后,
用showmodal显示登录窗体

==============================================================================

4、button上面的文字怎么样换行?
答:
button控件不行
bitbtn控件可以。
bitbtn1.caption:='aaaa'#13'bbbbb'

==============================================================================

5、怎么样判别焦点是否在某个控件上?
答:
if Tobject.focused then
//焦点在某某控件上
else

==============================================================================

6、怎么样在程序中使一个节点的子节点展开及收闭?
答:
treeview1.selected.Expanded; //判断节点的子节点是否展开True展开,否则闭拢
treeview1.selected.Expand(True);//子节点展开
treeview1.selected.collapse(True)://子节点闭拢

树节点全部展开:
procedure TForm1.Button1Click(Sender: TObject);
var node:TTreeNode;
begin
if treeview1.Items[0]<>nil then
begin
node:=treeview1.Items[0];
node.Expand(true);
while node.getNextSibling<>nil do
begin
node:=node.getNextSibling;
node.Expand(true);
end;
end;
end;


树节点全部收缩:
procedure TForm1.Button2Click(Sender: TObject);
var node:TTreeNode;
begin
if treeview1.Items[0]<>nil then
begin
node:=treeview1.Items[0];
node.Collapse(true);
while node.getNextSibling<>nil do
begin
node:=node.getNextSibling;
node.Collapse(true);
end;
end;
end;

==============================================================================

7、如何用delphi编程实现给access数据库加密码?
答:1,新建Project。
  2,在FORM中放入ADOConnection控件。
  3,双击ADOConnection控件,然后点击Build...按钮,在“提供者”页中选择“Microsoft Jet 4.0 OLE DB   Provider”,然后点击“下一步”按钮,在“连接”页中选择要连接的Access数据库的路径和数据库的文件名,这时如果点“测试连接”按钮时,出现“初始化提供者时发生错误,测试连接失败,密码无效”的错误提示。
  4,这时点“所有”页,然后双击“Jet OLEDB:Database Password”,出现对话框,添入密码后,选择“连接”页中的“测试连接”按钮,出现“测试连接成功”的对话框。把ADOConnection控件的LoginPromtp设为false.
  5,设置连接完成。

==============================================================================

8、如何判断Treeview中我选中的节点是否有子节点?如果没有给出提示啊?
答:
if Treeview.Selected.HasChildren then
//有
else
//无

var
Node :TTreeNode;
begin
Node :=TreeView1.Selected;
if Node.HasChildren then
....
对复杂的程序最好用Node过渡

==============================================================================

9、能否解释一下try...except...end及try...finally...end;?
1.(1)是用于扑捉异常,(2)是用于保证代码执行的完整性
2.(1)中finally处的代码不管什么情况都会被执行,(2)中except处的代码仅在发生异常时才会执行
3.try finally之间的代码虽可保证finally 和 end之间的程序能执行,但不能保证程序不崩溃,
而try except就不会使程序崩溃

==============================================================================

10、怎么样在主程序控制器中加入音乐?
在implementation下加入 mmsystem單元(windows多媒體函數動態聯結庫)。然後在的onShow,onCreate事件中編寫代碼:sndplaysound('sound.wav',snd_async)

==============================================================================

11、我在form1上有四个edit,输完后我想用下上箭头键进行上移下移?怎么办?
答:
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=vk_down then perform(WM_NEXTDLGCTL,0,0) else
if key=vk_up then perform(WM_NEXTDLGCTL,1,0);
end;

==============================================================================

12、如何用delphi5实现读文本文件指定的一行,并得到文本文件的总行数?谢谢!
答:
Delphi读文件文件一般使用Readln过程,如要读第3行可以这样:
var
i : Integer;
F: TextFile;
S: string;
begin
if OpenDialog1.Execute then { Display Open dialog box }
begin
AssignFile(F, OpenDialog1.FileName); { File selected in dialog }
Reset(F);
For i = 1 To 3 Do
Readln(F, S);
Edit1.Text := S; { Put string in a TEdit control }
CloseFile(F);
.
end;
要统计总行数,只能从头逐行读,直到文件尾(Eof函数为True),每读一行计数器加1。
不过由于文本文件的每行长度不相等,它不能象数据库文件那样想读那行就读哪行,只能顺序读。
上面的方法容易理解,也容易实现。如果希望提高速度,编程上要麻烦一些,可以以二进制方式打开文件,将所有内容读入一个内存变量,然后使用Pos函数查找其中的回车(#13)个数,这样可以快速地统计总行数并能快速地找到指定行。

==============================================================================

13、制作主窗口显示前的版权窗口
答:
在工程文件中选File->New Form新建一个窗口,设计好窗口的外观。给窗口起名为AboutBox,选Project->Options,将新建的窗口从自动建立中去掉。选View->Project Source,打开工程文件的源文件,在下面加入红色的句子。
Uses AboutBox
Var
lTime :TDateTime;
Begin
Application.Initialize();
AboutBox=TAboutBox.Create(AboutBox);
AboutBox.Show;
AboutBox.Update;
lTime=GetTickCount;
Application.CreateForm(TMainForm,MainForm);
while((GetTickCount-lTime) / 1000 <3) do;
AboutBox.Hide;
AboutBox.Free;
Application.Run;
end;

==============================================================================

14、Delphi中RichEdit的奥妙
  一、如何得知当前行号   
  用RichEdit(或者memo)控件制作文本编辑器时,通过访问lines?count属性可以得到总行数,但是若想知道光标当前所在行的行号就麻烦了,因为delphi没有提供这个属性。要实现这个编辑器必备功能,就须调用em_ LineFromChar。

  请试试下面的程序。
  先在窗口中布置一个RichEdit或者memo(命名为editor),以及一个button。在button的onclick事件中写入下列代码。
   var
   CurrentLine:Integer;
   begin
     CurrentLine:=Editor.Perform(em_ LineFromChar,SFFFF,0);   
     Application.MessageBox(PChar(′当前行号是′+IntToStr(CurrentLine)),′消息′,mb_ iconinformation);   
   end;
  需要注意的是,第一行的行号为零。

  二、如何撤消操作(undo)
  对于memo来说,实现undo是不需编程的,只要让popupmenu属性为空,运行时就能用鼠标右键激活一个常用操作菜单,其中包括撤消、剪切、复制、粘贴、删除和全选六项。  但可惜的是,这一招对于功能强大的RichEdit控件居然行不通,害得我们还要自己设计一个popupmemu。当你用 CutToClipBoard等语句轻松而顺利地完成了“剪切”等功能,接着便会无奈地发现,竟找不到undo或cancel之类的语句来执行“撤消”。  这时你需要这样处理:
    RichEdit1?Perform(EM_UNDO,0,0);
  另外还应检查是否允许撤消,从而开启或关闭弹出菜单中的“撤消”项:
    Undo1?Enabled:=RichEdit?
    Perform(EM_CANUNDO,0,0)<>0;   
以上程序在Delphi3中调试通过。  


==============================================================================

15、在主窗口中打开另一个独立的窗口,而这个被打开的窗口固定显示在..?
答:
procedure TForm2.FormCreate(Sender: TObject);
begin
form2.Hide;
self.Parent:=form1.Panel1;
end;

==============================================================================

16、SaveDialog1确认文件存不存在的办法?
答:
procedure TForm1.SaveDialog1CanClose(Sender: TObject;
var CanClose: Boolean);
begin
if FileExists(SaveDialog1.FileName) then //如果文件已经存在
if MessageDlg('文件已经存在,保存吗?', mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
Button2.Click ; //如果选择了覆盖,则退出,否则,重新让用户选择文件
end;

==============================================================================

17、正确关闭一个MDI子窗口?
答:
Delphi中MDI子窗口的关闭方式默认为缩小而不是关闭,所以当你单击子窗口右上角的关闭按钮时会发觉该子窗口只是最小化,而不是你预期的那样被关闭。解决办法是在子窗口的OnClose事件处理过程中加入如下代码,示例:

procedure ChildForm.OnClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;

  Delphi为一个Form的关闭行为指定了四种方式,分别是:

caNone 禁止Form被关闭
caHide Form不被关闭,但是被隐藏。被隐藏的Form仍然可以被程序访问。
caFree Form被关闭,并且释放其占用的资源。
caMinimize Form被最小化而不是被关闭,这是MDI子窗口的默认关闭行为。


==============================================================================

18、怎样记MDI子窗口不在母体运行时就被打开?
答:
在project下的options中forms里面除了form1外,其余的移到右边的框里,然后在调用显示的按钮下编写语句,以form2调用为例:
form2:=Tform2.create(self);
form2.show;

==============================================================================

19、限制FORM的大小
答:
在FORM私有声明部分加上如下一行:

procedure WMGetMinMaxInfo( var Message:TWMGetMinMaxInfo );message WM_GETMINMAXINFO;
在声明部分加上如下几行:
procedure TForm1.WMGetMinMaxInfo( var Message :TWMGetMinMaxInfo );
begin
with Message.MinMaxInfo^ do
begin
ptMaxSize.X := 200; {最大化时宽度}
ptMaxSize.Y := 200; {最大化时高度}
ptMaxPosition.X := 99; {最大化时左上角横坐标}
ptMaxPosition.Y := 99; {最大化时左上角纵坐标}
end;
Message.Result := 0; {告诉Windows你改变了 minmaxinfo}
inherited;
end;

==============================================================================

20、随机数生成法
答:
Randomize;
rn:=inttostr(random(9999));
rn1:=inttostr(random(9999));
.....

==============================================================================

21、怎样把程序隐藏起来,在WINDOWS界面上没有显示??
答:
在application.run之前加入application.showmain:=false!

==============================================================================

22、怎样将一个form1.free的form1窗体重新显示?
答:
form2:=TForm2.Create(application);
form2.Show;

如果你要创建的Form2窗体能嵌入一个Panel中,指定Parent:
form2:=TForm2.Create(application);
form2.Parent:=panel1;
form2.Show;

==============================================================================

23、我想在bitbtn上设快捷按钮Esc,怎么办?
答:
procedure TForm1.BitBtn1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=27 then
application.Terminate;
end;

设它的cancel属性为true就行了~~

==============================================================================

24、什么叫做托盘区?
答:
托盘区就是在windows的状态栏下方显示时钟、输入法状态的地方,

要把你的程序显示在托盘区:
下面是一个托盘类,只要把下面粘贴到文本文件中,改成TrayIcon.pas,使用时uses TrayIcon就可以了。

先声明一个全局变量:
var tray:TTrayNotifyIcon;

然后在窗体的OnCreate事件中:
tray:=TTrayNotifyIcon.Create(self);//将窗体创建为托盘
tray.Icon:=application.Icon;//定义托盘的显示图标
tray.IconVisible:=true;//托盘可见
tray.PopupMenu:=popmenu;//给托盘定义一个右击时的弹出菜单
tray.OnDblClick:=trayDblClick;//给托盘定义一个双击事件(当然要自己写了,不过多数情况只有一行,就是Form1.show);


unit TrayIcon;

interface

uses Windows, SysUtils, Messages, ShellAPI, Classes, Graphics, Forms, Menus,
StdCtrls, ExtCtrls;

type
ENotifyIconError = class(Exception);

TTrayNotifyIcon = class(TComponent)
private
FDefaultIcon: THandle;
FIcon: TIcon;
FHideTask: Boolean;
FHint: string;
FIconVisible: Boolean;
FPopupMenu: TPopupMenu;
FonClick: TNotifyEvent;
FOnDblClick: TNotifyEvent;
FNoShowClick: Boolean;
FTimer: TTimer;
Tnd: TNotifyIconData;
procedure SetIcon(Value: TIcon);
procedure SetHideTask(Value: Boolean);
procedure SetHint(Value: string);
procedure SetIconVisible(Value: Boolean);
procedure SetPopupMenu(Value: TPopupMenu);
procedure SendTrayMessage(Msg: DWORD; Flags: UINT);
function ActiveIconHandle: THandle;
procedure OnButtonTimer(Sender: TObject);
protected
procedure Loaded; override;
procedure LoadDefaultIcon; virtual;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Icon: TIcon read FIcon write SetIcon;
property HideTask: Boolean read FHideTask write SetHideTask default False;
property Hint: String read FHint write SetHint;
property IconVisible: Boolean read FIconVisible write SetIconVisible default False;
property PopupMenu: TPopupMenu read FPopupMenu write SetPopupMenu;
property onClick: TNotifyEvent read FonClick write FonClick;
property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick;
end;

implementation

{ TIconManager }
{ This class creates a hidden window which handles and routes }
{ tray icon messages }
type
TIconManager = class
private
FHWindow: HWnd;
procedure TrayWndProc(var Message: TMessage);
public
constructor Create;
destructor Destroy; override;
property HWindow: HWnd read FHWindow write FHWindow;
end;

var
IconMgr: TIconManager;
DDGM_TRAYICON: Cardinal;

constructor TIconManager.Create;
begin
FHWindow := AllocateHWnd(TrayWndProc);
end;

destructor TIconManager.Destroy;
begin
if FHWindow <> 0 then DeallocateHWnd(FHWindow);
inherited Destroy;
end;

procedure TIconManager.TrayWndProc(var Message: TMessage);
{ This allows us to handle all tray callback messages }
{ from within the context of the component. }
var
Pt: TPoint;
TheIcon: TTrayNotifyIcon;
begin
with Message do
begin
{ if it’s the tray callback message }
if (Msg = DDGM_TRAYICON) then
begin
TheIcon := TTrayNotifyIcon(WParam);
case lParam of
{ enable timer on first mouse down. }
{ onClick will be fired by OnTimer method, provided }
{ double click has not occurred. }
WM_LBUTTONDOWN: TheIcon.FTimer.Enabled := True;
{ Set no click flag on double click. This will supress }
{ the single click. }
WM_LBUTTONDBLCLK:
begin
TheIcon.FNoShowClick := True;
if Assigned(TheIcon.FOnDblClick) then TheIcon.FOnDblClick(Self);
end;
WM_RBUTTONDOWN:
begin
if Assigned(TheIcon.FPopupMenu) then
begin
{ Call to SetForegroundWindow is required by API }
SetForegroundWindow(IconMgr.HWindow);
{ Popup local menu at the cursor position. }
GetCursorPos(Pt);
TheIcon.FPopupMenu.Popup(Pt.X, Pt.Y);
{ Message post required by API to force task switch }
PostMessage(IconMgr.HWindow, WM_USER, 0, 0);
end;
end;
end;
end
else
{ If it isn’t a tray callback message, then call DefWindowProc }
Result := DefWindowProc(FHWindow, Msg, wParam, lParam);
end;
end;

{ TTrayNotifyIcon }

constructor TTrayNotifyIcon.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIcon := TIcon.Create;
FTimer := TTimer.Create(Self);
with FTimer do
begin
Enabled := False;
Interval := GetDoubleClickTime;
OnTimer := OnButtonTimer;
end;
{ Keep default windows icon handy... }
LoadDefaultIcon;
end;

destructor TTrayNotifyIcon.Destroy;
begin
if FIconVisible then SetIconVisible(False); // destroy icon
FIcon.Free; // free stuff
FTimer.Free;
inherited Destroy;
end;

function TTrayNotifyIcon.ActiveIconHandle: THandle;
{ Returns handle of active icon }
begin
{ If no icon is loaded, then return default icon }
if (FIcon.Handle <> 0) then
Result := FIcon.Handle
else
Result := FDefaultIcon;
end;

procedure TTrayNotifyIcon.LoadDefaultIcon;
{ Loads default window icon to keep it handy. }
{ This will allow the component to use the windows logo }
{ icon as the default when no icon is selected in the }
{ Icon property. }
begin
FDefaultIcon := LoadIcon(0, IDI_WINLOGO);
end;

procedure TTrayNotifyIcon.Loaded;
{ Called after component is loaded from stream }
begin
inherited Loaded;
{ if icon is supposed to be visible, create it. }
if FIconVisible then
SendTrayMessage(NIM_ADD, NIF_MESSAGE or NIF_ICON or NIF_TIP);
end;

procedure TTrayNotifyIcon.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = PopupMenu) then
PopupMenu := nil;
end;

procedure TTrayNotifyIcon.OnButtonTimer(Sender: TObject);
{ Timer used to keep track of time between two clicks of a }
{ double click. This delays the first click long enough to }
{ ensure that a double click hasn’t occurred. The whole }
{ point of these gymnastics is to allow the component to }
{ receive onClicks and OnDblClicks independently. }
begin
{ Disable timer because we only want it to fire once. }
FTimer.Enabled := False;
{ if double click has not occurred, then fire single click. }
if (not FNoShowClick) and Assigned(FonClick) then
FonClick(Self);
FNoShowClick := False; // reset flag
end;

procedure TTrayNotifyIcon.SendTrayMessage(Msg: DWORD; Flags: UINT);
{ This method wraps up the call to the API’s Shell_NotifyIcon }
begin
{ Fill up record with appropriate values }
with Tnd do
begin
cbSize := SizeOf(Tnd);
StrPLCopy(szTip, PChar(FHint), SizeOf(szTip));
uFlags := Flags;
uID := UINT(Self);
Wnd := IconMgr.HWindow;
uCallbackMessage := DDGM_TRAYICON;
hIcon := ActiveIconHandle;
end;
Shell_NotifyIcon(Msg, @Tnd);
end;

procedure TTrayNotifyIcon.SetHideTask(Value: Boolean);
{ Write method for HideTask property }
const
{ Flags to show application normally or hide it }
ShowArray: array[Boolean] of integer = (sw_ShowNormal, sw_Hide);
begin
if FHideTask <> Value then
begin
FHideTask := Value;
{ Don’t do anything in design mode }
if not (csDesigning in ComponentState) then
ShowWindow(Application.Handle, ShowArray[FHideTask]);
end;
end;

procedure TTrayNotifyIcon.SetHint(Value: string);
{ Set method for Hint property }
begin
if FHint <> Value then
begin
FHint := Value;
if FIconVisible then
{ Change hint on icon on tray notification area }
SendTrayMessage(NIM_MODIFY, NIF_TIP);
end;
end;

procedure TTrayNotifyIcon.SetIcon(Value: TIcon);
{ Write method for Icon property. }
begin
FIcon.Assign(Value); // set new icon
{ Change icon on notification tray }
if FIconVisible then SendTrayMessage(NIM_MODIFY, NIF_ICON);
end;

procedure TTrayNotifyIcon.SetIconVisible(Value: Boolean);
{ Write method for IconVisible property }
const
{ Flags to add or delete a tray notification icon }
MsgArray: array[Boolean] of DWORD = (NIM_DELETE, NIM_ADD);
begin
if FIconVisible <> Value then
begin
FIconVisible := Value;
{ Set icon as appropriate }
SendTrayMessage(MsgArray[Value], NIF_MESSAGE or NIF_ICON or NIF_TIP);
end;
end;

procedure TTrayNotifyIcon.SetPopupMenu(Value: TPopupMenu);
{ Write method for PopupMenu property }
begin
FPopupMenu := Value;
if Value <> nil then Value.FreeNotification(Self);
end;

const
{ String to identify registered window message }
TrayMsgStr = ’DDG.TrayNotifyIconMsg’;

initialization
{ Get a unique windows message ID for tray callback }
DDGM_TRAYICON := RegisterWindowMessage(TrayMsgStr);
IconMgr := TIconManager.Create;
finalization
IconMgr.Free;
end.

==============================================================================

25、关于窗体释放的问题(formX.free)?
答:
这个我知道,模式窗口用:form2 := TForm2.Create(Application);
try
if form2.showModal = mrOK then
{do Something}
finally
form2.free;
form2 := nil;
end; 非模式窗口用:if not Assigned(form2) then
form2 := Tfrom2.Create(Application);
form2.show;

//然后在form2的Close事件中加入以下句
Action := caFree;

//在from2的Destory事件中加入以下句
form2 := nil; 搞定!!!

==============================================================================

26、关于MDI窗体的问题?
答:
我不知道是如何实现,但我知道一个方法可以实现同样的功能,在打开子窗体前加一句
button1.SendToBack;

==============================================================================

27、小数点'.'的键号是什么?回车是#13,'.'是什么?
答:
你可以用此得出所有键的值procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
label1.caption:=IntToStr(key);
end;

==============================================================================
==============================================================================

1、判断机器是否网络状态
答:
uses WinInet;
procedure TForm1.Button1Click(Sender: TObject);
function GetOnlineStatus : Boolean;
var ConTypes : Integer;
begin
ConTypes := INTERNET_CONNECTION_MODEM + INTERNET_CONNECTION_LAN + INTERNET_CONNECTION_PROXY;
if (InternetGetConnectedState(@ConTypes, 0) = False)
then Result := False
else Result := True;
end;
begin
if not GetOnlineStatus then ShowMessage('Not Connected');
end;

==============================================================================

2、[DELPHI]窗体渐渐出现
答:
AnimateWindow(Handle,1000,AW_CENTER);
//在窗体创建事件中

==============================================================================

3、如何取得一台机器的CPU占用率 ?
答:
使用下面的方法
interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

const
SystemBasicInformation = 0;
SystemPerformanceInformation = 2;
SystemTimeInformation = 3;

type
TPDWord = ^DWORD;

TSystem_Basic_Information = packed record
dwUnknown1: DWORD;
uKeMaximumIncrement: ULONG;
uPageSize: ULONG;
uMmNumberOfPhysicalPages: ULONG;
uMmLowestPhysicalPage: ULONG;
uMmHighestPhysicalPage: ULONG;
uAllocationGranularity: ULONG;
pLowestUserAddress: Pointer;
pMmHighestUserAddress: Pointer;
uKeActiveProcessors: ULONG;
bKeNumberProcessors: byte;
bUnknown2: byte;
wUnknown3: word;
end;

type
TSystem_Performance_Information = packed record
liIdleTime: LARGE_INTEGER; {LARGE_INTEGER}
dwSpare: array[0..75] of DWORD;
end;

type
TSystem_Time_Information = packed record
liKeBootTime: LARGE_INTEGER;
liKeSystemTime: LARGE_INTEGER;
liExpTimeZoneBias: LARGE_INTEGER;
uCurrentTimeZoneId: ULONG;
dwReserved: DWORD;
end;

var
NtQuerySystemInformation: function(infoClass: DWORD;
buffer: Pointer;
bufSize: DWORD;
returnSize: TPDword): DWORD; stdcall = nil;


liOldIdleTime: LARGE_INTEGER = ();
liOldSystemTime: LARGE_INTEGER = ();
SysBaseInfo: TSystem_Basic_Information;
SysPerfInfo: TSystem_Performance_Information;
SysTimeInfo: TSystem_Time_Information;
status: Longint; {long}
dbSystemTime: Double;
dbIdleTime: Double;
function GetCPUUsage:Double;
implementation
function Li2Double(x: LARGE_INTEGER): Double;
begin
Result := x.HighPart * 4.294967296E9 + x.LowPart
end;

function GetCPUUsage:Double;
var
bLoopAborted : boolean;
begin
if @NtQuerySystemInformation = nil then
NtQuerySystemInformation := GetProcAddress(GetModuleHandle(‘ntdll.dll‘),
‘NtQuerySystemInformation‘);
// get number of processors in the system
status := NtQuerySystemInformation(SystemBasicInformation, @SysBaseInfo, SizeOf(SysBaseInfo), nil);
if status <> 0 then Exit;
// Show some information
{with SysBaseInfo do
begin
ShowMessage(
Format(‘uKeMaximumIncrement: %d‘#13‘uPageSize: %d‘#13+
‘uMmNumberOfPhysicalPages: %d‘+#13+‘uMmLowestPhysicalPage: %d‘+#13+
‘uMmHighestPhysicalPage: %d‘+#13+‘uAllocationGranularity: %d‘#13+
‘uKeActiveProcessors: %d‘#13‘bKeNumberProcessors: %d‘,
[uKeMaximumIncrement, uPageSize, uMmNumberOfPhysicalPages,
uMmLowestPhysicalPage, uMmHighestPhysicalPage, uAllocationGranularity,
uKeActiveProcessors, bKeNumberProcessors]));
end;
}
bLoopAborted := False;
while not bLoopAborted do
begin
// get new system time
status := NtQuerySystemInformation(SystemTimeInformation, @SysTimeInfo, SizeOf(SysTimeInfo), 0);
if status <> 0 then Exit;
// get new CPU‘s idle time
status := NtQuerySystemInformation(SystemPerformanceInformation, @SysPerfInfo, SizeOf(SysPerfInfo), nil);
if status <> 0 then Exit;
// if it‘s a first call - skip it
if (liOldIdleTime.QuadPart <> 0) then
begin
// CurrentValue = NewValue - OldValue
dbIdleTime := Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
dbSystemTime := Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);
// CurrentCpuIdle = IdleTime / SystemTime
dbIdleTime := dbIdleTime / dbSystemTime;
// CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
dbIdleTime := 100.0 - dbIdleTime * 100.0 / SysBaseInfo.bKeNumberProcessors + 0.5;
// Show Percentage
//Form1.Label1.Caption := FormatFloat(‘CPU Usage: 0.0 %‘,dbIdleTime);
//Application.ProcessMessages;
// Abort if user pressed ESC or Application is terminated
Result:=dbIdleTime;
bLoopAborted:=True;
//bLoopAborted := (GetKeyState(VK_ESCAPE) and 128 = 128) or Application.Terminated;
end;
// store new CPU‘s idle and
 

==============================================================================

4、动态生成控件?
答:
var
TeSpeedButtonX:TTeSpeedButton;
begin
TeSpeedButtonX:=TTeSpeedButton.Create(nil);
TeSpeedButtonX.Caption:='标题';
TeSpeedButtonX.Name:='按钮'+inttostr(X);
TeSpeedButtonX.Parent:=Tetoolbar2;
X:=X+1;
end;
==============================================================================

5、我动态创建了多个button,使用时,我怎么判断出用户点击的是哪个button呢?button的各项属性都边成最后创建的那个button的了,怎么办哦?
答1:
教你一招,先设置每个button的tag属性.然后在onclick事件中用(sender as button).tag来判断,相信我,没错的!

答2:
如果你生成的控件不是很多的话,最简单的方法就是,假如你生成控件的父控件是FORM1,利用循环判断控件是否等于 FORM1.ACTIVECONTROL,我就是这么用的。ACTIVECONTROL就是记录当前被点击的控件,你也可以直接用它,不过直接只能用到 CONTROL的一般属性和方法,循环判断的话就可以用到你生成控件的相关属性。

==============================================================================

6、窗体释放问题
答:
在Form2.OnClose事件中
Action:=caFree;

function   Pos(SubStr:   string;   Str:   string):   Integer;   //返回SubStr在Str中的位置 
  
  function   StrPos(Str1:   PChar;   Str2:   PChar):   PChar;   //返回Str2在Str1中的指针 
  
  Pos('3',   '123456')   =   3 
  StrPos('123456',   '3')   =   '3456' 
                  ~~~~~~注意都是PChar  

 


 2003-11-19 13:53:23    数据网格自动适应宽度

///////源代码开始
uses
  Math;

function DBGridRecordSize(mColumn: TColumn): Boolean;
{ 返回记录数据网格列显示最大宽度是否成功 }
begin
  Result := False;
  if not Assigned(mColumn.Field) then Exit;
  mColumn.Field.Tag := Max(mColumn.Field.Tag,
    TDBGrid(mColumn.Grid).Canvas.TextWidth(mColumn.Field.DisplayText));
  Result := True;
end; { DBGridRecordSize }

function DBGridAutoSize(mDBGrid: TDBGrid; mOffset: Integer = 5): Boolean;
{ 返回数据网格自动适应宽度是否成功 }
var
  I: Integer;
begin
  Result := False;
  if not Assigned(mDBGrid) then Exit;
  if not Assigned(mDBGrid.DataSource) then Exit;
  if not Assigned(mDBGrid.DataSource.DataSet) then Exit;
  if not mDBGrid.DataSource.DataSet.Active then Exit;
  for I := 0 to mDBGrid.Columns.Count - 1 do begin
    if not mDBGrid.Columns[I].Visible then Continue;
    if Assigned(mDBGrid.Columns[I].Field) then
      mDBGrid.Columns[I].Width := Max(mDBGrid.Columns[I].Field.Tag,
        mDBGrid.Canvas.TextWidth(mDBGrid.Columns[I].Title.Caption)) + mOffset
    else mDBGrid.Columns[I].Width :=
      mDBGrid.Canvas.TextWidth(mDBGrid.Columns[I].Title.Caption) + mOffset;
    mDBGrid.Refresh;
  end;
  Result := True;
end; { DBGridAutoSize }
///////源代码结束

///////使用示例开始
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  DBGridRecordSize(Column);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  DBGridAutoSize(DBGrid1);
end;
///////使用示例结束

原创粉丝点击