zoukankan      html  css  js  c++  java
  • Delphi技巧集

    ◇[DELPHI]网络邻居复制文件

      uses shellapi;

      copyfile(pchar('newfile.txt'),pchar('//computername/direction/targer.txt'),false);

    ◇[DELPHI]取得WINDOWS目录

      uses shellapi;

      var windir:array[0..255] of char;

      getwindowsdirectory(windir,sizeof(windir));

      或者从注册表中读取,位置:

      HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion

      SystemRoot键,取得如:C:\WINDOWS

    ◇[DELPHI]在FORM或其他容器上画线

      var x,y:array [0..50] of integer;

      canvas.pen.color:=clred;

      canvas.pen.style:=psDash;

      form1.canvas.moveto(trunc(x[i]),trunc(y[i]));

      form1.canvas.lineto(trunc(x[j]),trunc(y[j]));

    ◇[DELPHI]字符串列表使用

    var tips:tstringlist;

    tips:=tstringlist.create;

    tips.loadfromfile('filename.txt');

    edit1.text:=tips[0];

    tips.add('last line addition string');

    tips.insert(1,'insert string at NO 2 line');

    tips.savetofile('newfile.txt');

    tips.free;

    ◇[DELPHI]简单的剪贴板操作

    richedit1.selectall;

    richedit1.copytoclipboard;

    richedit1.cuttoclipboard;

    edit1.pastefromclipboard;

    ◇[DELPHI]关于文件、目录操作

    Chdir('c:\abcdir');转到目录

    Mkdir('dirname');建立目录

    Rmdir('dirname');删除目录

    GetCurrentDir;//取当前目录名,无'\'

    Getdir(0,s);//取工作目录名s:='c:\abcdir';

    Deletfile('abc.txt');//删除文件

    Renamefile('old.txt','new.txt');//文件更名

    ExtractFilename(filelistbox1.filename);//取文件名

    ExtractFileExt(filelistbox1.filename);//取文件后缀

    ◇[DELPHI]处理文件属性

    attr:=filegetattr(filelistbox1.filename);

    if (attr and faReadonly)=faReadonly then ... //只读

    if (attr and faSysfile)=faSysfile then ... //系统

    if (attr and faArchive)=faArchive then ... //存档

    if (attr and faHidden)=faHidden then ... //隐藏

    ◇[DELPHI]执行程序外文件

    WINEXEC//调用可执行文件

    winexec('command.com /c copy *.* c:\',SW_Normal);

    winexec('start abc.txt');

    ShellExecute或ShellExecuteEx//启动文件关联程序

    function executefile(const filename,params,defaultDir:string;showCmd:integer):THandle;

    ExecuteFile('C:\abc\a.txt','x.abc','c:\abc\',0);

    ExecuteFile('http://tingweb.yeah.net','','',0);

    ExecuteFile('mailto:tingweb@wx88.net','','',0);

    ◇[DELPHI]取得系统运行的进程名

    var hCurrentWindow:HWnd;szText:array[0..254] of char;

    begin

    hCurrentWindow:=Getwindow(handle,GW_HWndFrist);

    while hCurrentWindow <> 0 do

    begin

    if Getwindowtext(hcurrnetwindow,@sztext,255)>0 then listbox1.items.add(strpas(@sztext));

    hCurrentWindow:=Getwindow(hCurrentwindow,GW_HWndNext);

    end;

    end;

    ◇[DELPHI]关于类型转换函数

    FloatToStr//浮点转字符串

    FloatToStrF//带格式的浮点转字符串

    IntToHex//整数转16进制

    TimeToStr

    DateToStr

    DateTimeToStr

    FmtStr//按指定格式输出字符串

    FormatDateTime('YYYY-MM-DD,hh-mm-ss',DATE);

    ◇[DELPHI]字符串的过程和函数

    Insert(obj,target,pos);//字符串target插入在pos的位置。如插入结果大于target最大长度,多出字符将被截掉。如Pos在255以外,会产生运行错。例如,st:='Brian',则Insert('OK',st,2)会使st变为'BrOKian'。

    Delete(st,pos,Num);//从st串中的pos(整型)位置开始删去个数为Num(整型)个字符的子字串。例如,st:='Brian',则Delete(st,3,2)将变为Brn。

    Str(value,st);//将数值value(整型或实型)转换成字符串放在st中。例如,a=2.5E4时,则str(a:10,st)将使st的值为' 25000'。

    Val(st,var,code);//把字符串表达式st转换为对应整型或实型数值,存放在var中。St必须是一个表示数值的字符串,并符合数值常数的规则。在转换过程中,如果没有检测出错误,变量code置为0,否则置为第一个出错字符的位置。例如,st:=25.4E3,x是一个实型变量,则val(st,x,code)将使X值为25400,code值为0。

    Copy(st.pos.num);//返回st串中一个位置pos(整型)处开始的,含有num(整型)个字符的子串。如果pos大于st字符串的长度,那就会返回一个空串,如果pos在255以外,会引起运行错误。例如,st:='Brian',则Copy(st,2,2)返回'ri'。

    Concat(st1,st2,st3……,stn);//把所有自变量表示出的字符串按所给出的顺序连接起来,并返回连接后的值。如果结果的长度255,将产生运行错误。例如,st1:='Brian',st2:=' ',st3:='Wilfred',则Concat(st1,st2,st3)返回'Brian Wilfred'。

    Length(st);//返回字符串表达式st的长度。例如,st:='Brian',则Length(st)返回值为5。

    Pos(obj,target);//返回字符串obj在目标字符串target的第一次出现的位置,如果target没有匹配的串,Pos函数的返回值为0。例如,target:='Brian Wilfred',则Pos('Wil',target)的返回值是7,Pos('hurbet',target)的返回值是0。

    ◇[DELPHI]关于处理注册表

    uses Registry;

    var reg:Tregistry;

    reg:=Tregistry.create;

    reg.rootkey:='HKey_Current_User';

    reg.openkey('Control Panel\Desktop',false);

    reg.WriteString('Title Wallpaper','0');

    reg.writeString('Wallpaper',filelistbox1.filename);

    reg.closereg;

    reg.free;

    ◇[DELPHI]关于键盘常量名

    VK_BACK/VK_TAB/VK_RETURN/VK_SHIFT/VK_CONTROL/VK_MENU/VK_PAUSE/VK_ESCAPE

    /VK_SPACE/VK_LEFT/VK_RIGHT/VK_UP/VK_DOWN

    F1--F12:$70(112)--$7B(123)

    A-Z:$41(65)--$5A(90)

    0-9:$30(48)--$39(57)

    ◇[DELPHI]操作Cookie

    response.cookies("name").domain:='http://www.086net.com';

    with response.cookies.add do

    begin

    name:='username';

    value:='username';

    end

    ◇[DELPHI]增加到文档菜单连接

    uses shellapi,shlOBJ;

    shAddToRecentDocs(shArd_path,pchar(filepath));//增加连接

    shAddToRecentDocs(shArd_path,nil);//清空

    ◇[杂类]备份智能ABC输入法词库

    windows\system\user.rem

    windows\system\tmmr.rem

    ◇[DELPHI]判断鼠标按键

    if GetAsyncKeyState(VK_LButton)<>0 then ... //左键

    if GetAsyncKeyState(VK_MButton)<>0 then ... //中键

    if GetAsyncKeyState(VK_RButton)<>0 then ... //右键

    ◇[DELPHI]设置窗体的最大显示

    onFormCreate事件

    self.=screen.width;

    self.height:=screen.height;

    ◇[DELPHI]按键接受消息

    OnCreate事件中处理:Application.OnMessage:=MyOnMessage;

    procedure TForm1.MyOnMessage(var MSG:TMSG;var Handle:Boolean);

    begin

    if msg.message=256 then ... //ANY键

    if msg.message=112 then ... //F1

    if msg.message=113 then ... //F2

    end;

    ◇[杂类]隐藏共享文件夹

    共享效果:可访问,但不可见(在资源管理、网络邻居中)

    取共享名为:direction$

    访问://computer/dirction/

    ◇[Java Script]Java Script网页常用效果

    网页60秒定时关闭

    <script language="java script"><!--

    settimeout('window.close();',60000)

    --></script>

    关闭窗口

    <a href="/" onclick="javascript:window.close();return false;">关闭</a>

    定时转URL

    <meta http-equiv="refresh" content="40;url=http://www.086net.com">

    设为首页

    <a onclick="this.style.behavior='url(#default#homepage)';this.sethomepage('http://086net.com');"href="#">设为首页</a>

    收藏本站

    <a href="javascript:window.external.addfavorite('http://086net.com','[未名码头]')">收藏本站</a>

    加入频道

    <a href="javascript:window.external.addchannel('http://086net.com')">加入频道</a>

    ◇[DELPHI]文本编辑相关

    checkbox1.checked:=not checkbox1.checked;

    if checkbox1.checked then richedit1.font.style:=richedit1.font.style+[fsBold] else richedit1.font.style:=richedit1.font.style-[fsBold]//粗体

    if checkbox1.checked then richedit1.font.style:=richedit1.font.style+[fsItalic] else richedit1.font.style:=richedit1.font.style-[fsItalic]//斜体

    if checkbox1.checked then richedit1.font.style:=richedit1.font.style+[fsUnderline] else richedit1.font.style:=richedit1.font.style-[fsUnderline]//下划线

    memo1.alignment:=taLeftJustify;//居左

    memo1.alignment:=taRightJustify;//居右

    memo1.alignment:=taCenter;//居中

    ◇[DELPHI]随机产生文本色

    randomize;//随机种子

    memo1.font.color:=rgb(random(255),random(255),random(255));

    ◇[DELPHI]文件名的非法字符过滤

    for i:=1 to length(s) do

    if s[i] in ['\','/',':','*','?','<','>','|'] then

    ◇[DELPHI]转换函数的定义及说明

    datetimetofiledate (datetime:Tdatetime):longint; 将Tdatetime格式的日期时间值转换成DOS格式的日期时间值

    datetimetostr (datetime:Tdatetime):string; 将Tdatatime格式变量转换成字符串,如果datetime参数不包含日期值,返回字符串日期显示成为00/00/00,如果datetime参数中没有时间值,返回字符串中的时间部分显示成为00:00:00 AM

    datetimetostring (var result string;

    const format:string;

    datetime:Tdatetime); 根据给定的格式字符串转换时间和日期值,result为结果字符串,format为转换格式字符串,datetime为日期时间值

    datetostr (date:Tdatetime) 使用shortdateformat全局变量定义的格式字符串将date参数转换成对应的字符串

    floattodecimal (var result:Tfloatrec;value:

    extended;precision,decimals:

    integer); 将浮点数转换成十进制表示

    floattostr (value:extended):string 将浮点数value转换成字符串格式,该转换使用普通数字格式,转换的有效位数为15位。

    floattotext (buffer:pchar;value:extended;

    format:Tfloatformat;precision,

    digits:integer):integer; 用给定的格式、精度和小数将浮点值value转换成十进制表示形式,转换结果存放于buffer参数中,函数返回值为存储到buffer中的字符位数,buffer是非0结果的字符串缓冲区。

    floattotextfmt (buffer:pchar;value:extended;

    format:pchar):integer 用给定的格式将浮点值value转换成十进制表示形式,转换结果存放于buffer参数中,函数返回值为存储到buffer中的字符位数。

    inttohex (value:longint;digits:integer):

    string; 将给定的数值value转换成十六进制的字符串。参数digits给出转换结果字符串包含的数字位数。

    inttostr (value:longint):string 将整数转换成十进制形式字符串

    strtodate (const S:string):Tdatetime 将字符串转换成日期值,S必须包含一个合法的格式日期的字符串。

    strtodatetime (const S:string):Tdatetime 将字符串S转换成日期时间格式,S必须具有MM/DD/YY HH:MM:SS[AM|PM]格式,其中日期和时间分隔符与系统时期时间常量设置相关。如果没有指定AM或PM信息,表示使用24小时制。

    strtofloat (const S:string):extended; 将给定的字符串转换成浮点数,字符串具有如下格式:

    [+|-]nnn…[.]nnn…[<+|-><E|e><+|->nnnn]

    strtoint (const S:string):longint 将数字字符串转换成整数,字符串可以是十进制或十六进制格式,如果字符串不是一个合法的数字字符串,系统发生ECONVERTERROR异常

    strtointdef (const S:string;default:

    longint):longint; 将字符串S转换成数字,如果不能将S转换成数字,strtointdef函数返回参数default的值。

    strtotime (const S:string):Tdatetime 将字符串S转换成TDATETIME值,S具有HH:MM:SS[AM|PM]格式,实际的格式与系统的时间相关的全局变量有关。

    timetostr (time:Tdatetime):string; 将参数TIME转换成字符串。转换结果字符串的格式与系统的时间相关常量的设置有关。

    ◇[DELPHI]程序不出现在ALT+CTRL+DEL

    在implementation后添加声明:

    function RegisterServiceProcess(dwProcessID, dwType: Integer): Integer; stdcall; external 'KERNEL32.DLL';

    RegisterServiceProcess(GetCurrentProcessID, 1);//隐藏

    RegisterServiceProcess(GetCurrentProcessID, 0);//显示

    用ALT+DEL+CTRL看不见

    ◇[DELPHI]程序不出现在任务栏

    uses windows

    var

    ExtendedStyle : Integer;

    begin

    Application.Initialize;

    //==============================================================

    ExtendedStyle := GetWindowLong (Application.Handle, GWL_EXSTYLE);

    SetWindowLong(Application.Handle, GWL_EXSTYLE, ExtendedStyle OR WS_EX_TOOLWINDOW

    AND NOT WS_EX_APPWINDOW);

    //===============================================================

    Application.CreateForm(TForm1, Form1);

    Application.Run;

    end.

    ◇[DELPHI]如何判断拨号网络是开还是关

    if GetSystemMetrics(SM_NETWORK) AND $01 = $01 then

    showmessage('在线!')

    else showmessage('不在线!');

    ◇[DELPHI]实现IP到域名的转换

    function GetDomainName(Ip:string):string;

    var

    pH:PHostent;

    data:twsadata;

    ii:dword;

    begin

    WSAStartup($101, Data);

    ii:=inet_addr(pchar(ip));

    pH:=gethostbyaddr(@ii,sizeof(ii),PF_INET);

    if (ph<>nil) then

    result:=pH.h_name

    else

    result:='';

    WSACleanup;

    end;

    ◇[DELPHI]处理“右键菜单”方法

    var

    reg: TRegistry;

    begin

    reg := TRegistry.Create;

    reg.RootKey:=HKEY_CLASSES_ROOT;

    reg.OpenKey('*\shell\check\command', true);

    reg.WriteString('', '"' + application.ExeName + '" "%1"');

    reg.CloseKey;

    reg.OpenKey('*\shell\diary', false);

    reg.WriteString('', '操作(&C)');

    reg.CloseKey;

    reg.Free;

    showmessage('DONE!');

    end;

    ◇[DELPHI]发送虚拟键值ctrl V

    procedure sendpaste;

    begin

    keybd_event(VK_Control, MapVirtualKey(VK_Control, 0), 0, 0);

    keybd_event(ord('V'), MapVirtualKey(ord('V'), 0), 0, 0);

    keybd_event(ord('V'), MapVirtualKey(ord('V'), 0), KEYEVENTF_KEYUP, 0);

    keybd_event(VK_Control, MapVirtualKey(VK_Control, 0), KEYEVENTF_KEYUP, 0);

    end;

    ◇[DELPHI]当前的光驱的盘符

    procedure getcdrom(var cd:char);

    var

    str:string;

    drivers:integer;

    driver:char;

    i,temp:integer;

    begin

    drivers:=getlogicaldrives;

    temp:=(1 and drivers);

    for i:=0 to 26 do

    begin

    if temp=1 then

    begin

    driver:=char(i+integer('a'));

    str:=driver+':';

    if getdrivetype(pchar(str))=drive_cdrom then

    begin

    cd:=driver;

    exit;

    end;

    end;

    drivers:=(drivers shr 1);

    temp:=(1 and drivers);

    end;

    end;

    ◇[DELPHI]字符的加密与解密

    function cryptstr(const s:string; stype: dword):string;

    var

    i: integer;

    fkey: integer;

    begin

    result:='';

    case stype of

    0: setpass;

    begin

    randomize;

    fkey := random($ff);

    for i:=1 to length(s) do

    result := result+chr( ord(s[i]) xor i xor fkey);

    result := result + char(fkey);

    end;

    1: getpass

    begin

    fkey := ord(s[length(s)]);

    for i:=1 to length(s) - 1 do

    result := result+chr( ord(s[i]) xor i xor fkey);

    end;

    end;

    ◇[DELPHI]向其他应用程序发送模拟键

    var

    h: THandle;

    begin

    h := FindWindow(nil, '应用程序标题');

    PostMessage(h, WM_KEYDOWN, VK_F9, 0);//发送F9键

    end;

    ◇[DELPHI]DELPHI 支持的DAO数据格式

    td.Fields.Append(td.CreateField ('dbBoolean',dbBoolean,0));

    td.Fields.Append(td.CreateField ('dbByte',dbByte,0));

    td.Fields.Append(td.CreateField ('dbInteger',dbInteger,0));

    td.Fields.Append(td.CreateField ('dbLong',dbLong,0));

    td.Fields.Append(td.CreateField ('dbCurrency',dbCurrency,0));

    td.Fields.Append(td.CreateField ('dbSingle',dbSingle,0));

    td.Fields.Append(td.CreateField ('dbDouble',dbDouble,0));

    td.Fields.Append(td.CreateField ('dbDate',dbDate,0));

    td.Fields.Append(td.CreateField ('dbBinary',dbBinary,0));

    td.Fields.Append(td.CreateField ('dbText',dbText,0));

    td.Fields.Append(td.CreateField ('dbLongBinary',dbLongBinary,0));

    td.Fields.Append(td.CreateField ('dbMemo',dbMemo,0));

    td.Fields['ID'].Set_Attributes(dbAutoIncrField);//自增字段

    ◇[DELPHI]DELPHI配置MS SQL 7和BDE步骤

    第一步,配置ODBC:

    先在ODBC 中设数据源,安装过SQL Server7.0 后,ODBC中有一项"系统DSN"应该有两项

    数据源,一个是MQIS,一个是LocalSever,任选一个选后点击配置按钮,不知你的SQL7.0

    是不是安装在本地机器上,如果是的话直接进行下一步,如果不是,在服务器一栏中填上

    Server,然后进行下一步,填写登录ID 和密码(登录ID,和密码是在SQL7.0中的用户选项

    中设的)。

    第二步,配置BDE:

    打开Delphi的BDE,然后点击MQIS 或 LocalServer,就会提示用户名和密码,这和

    ODBC的用户名和密码是一样的,填上就行了。

    第三步,配置程序:

    如果用的是TTable,就在TTable的DatabaseName中选择MQIS 或LocalServer,然后在

    TableName中选择Sale就行了,然后将Active改为True,Delphi弹出提示对话,填入用户

    名和密码。

    如果用的是TQuery,在TQuery上点击右键,再击"SQL Builder",这是以界面方式配置

    SQL语句,或者在TQuery的SQL中填入SQL语句。最后,别忘了将Active改为True。

    在运行也可能配置TQuery,具体见Delphi帮助。

    ◇[DELPHI]得到图像上某一点的RGB值

    procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton;

    Shift: TShiftState; X, Y: Integer);

    var

    red,green,blue:byte ;

    i:integer;

    begin

    i:= image1.Canvas.Pixels[x,y];

    Blue:= GetBValue(i);

    Green:= GetGValue(i):

    Red:= GetRValue(i);

    Label1.Caption:=inttostr(Red);

    Label2.Caption:=inttostr(Green);

    Label3.Caption:=inttostr(Blue);

    end;

    ◇[DELPHI]关于日期格式分解转换

    var year,month,day:word;now2:Tdatatime;

    now2:=date();

    decodedate(now2,year,month,day);

    lable1.Text :=inttostr(year)+'年'+inttostr(month)+'月'+inttostr(day)+'日';

    ◇[DELPHI]如何判断当前网络连接方式

    判断结果是MODEM、局域网或是代理服务器方式。

    uses wininet;

    Function ConnectionKind :boolean;

    var flags: dword;

    begin

    Result := InternetGetConnectedState(@flags, 0);

    if Result then

    begin

    if (flags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then

    begin

    showmessage('Modem');

    end;

    if (flags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then

    begin

    showmessage('LAN');

    end;

    if (flags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then

    begin

    showmessage('Proxy');

    end;

    if (flags and INTERNET_CONNECTION_MODEM_BUSY)=INTERNET_CONNECTION_MODEM_BUSY then

    begin

    showmessage('Modem Busy');

    end;

    end;

    end;

    ◇[DELPHI]如何判断字符串是否是有效EMAIL地址

    function IsEMail(EMail: String): Boolean;

    var s: String;ETpos: Integer;

    begin

    ETpos:= pos('@', EMail);

    if ETpos > 1 then

    begin

    s:= copy(EMail,ETpos+1,Length(EMail));

    if (pos('.', s) > 1) and (pos('.', s) < length(s)) then

    Result:= true else Result:= false;

    end

    else

    Result:= false;

    end;

    ◇[DELPHI]判断系统是否连接INTERNET

    需要引入URL.DLL中的InetIsOffline函数。

    函数申明为:

    function InetIsOffline(Flag: Integer): Boolean; stdcall; external 'URL.DLL';

    然后就可以调用函数判断系统是否连接到INTERNET

    if InetIsOffline(0) then ShowMessage('not connected!')

    else ShowMessage('connected!');

    该函数返回TRUE如果本地系统没有连接到INTERNET。

    附:

    大多数装有IE或OFFICE97的系统都有此DLL可供调用。

    InetIsOffline

    BOOL InetIsOffline(

    DWORD dwFlags,

    );

    ◇[DELPHI]简单地播放和暂停WAV文件

    uses mmsystem;

    function PlayWav(const FileName: string): Boolean;

    begin

    Result := PlaySound(PChar(FileName), 0, SND_ASYNC);

    end;

    procedure StopWav;

    var

    buffer: array[0..2] of char;

    begin

    buffer[0] := #0;

    PlaySound(Buffer, 0, SND_PURGE);

    end;

    ◇[DELPHI]取机器BIOS信息

    with Memo1.Lines do

    begin

    Add('MainBoardBiosName:'+^I+string(Pchar(Ptr($FE061))));

    Add('MainBoardBiosCopyRight:'+^I+string(Pchar(Ptr($FE091))));

    Add('MainBoardBiosDate:'+^I+string(Pchar(Ptr($FFFF5))));

    Add('MainBoardBiosSerialNo:'+^I+string(Pchar(Ptr($FEC71))));

    end;

    ◇[DELPHI]网络下载文件

    uses UrlMon;

    function DownloadFile(Source, Dest: string): Boolean;

    begin

    try

    Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0;

    except

    Result := False;

    end;

    end;

    if DownloadFile('http://www.borland.com/delphi6.zip, 'c:\kylix.zip') then

    ShowMessage('Download succesful')

    else ShowMessage('Download unsuccesful')

    ◇[DELPHI]解析服务器IP地址

    uses winsock

    function IPAddrToName(IPAddr : String): String;

    var

    SockAddrIn: TSockAddrIn;

    HostEnt: PHostEnt;

    WSAData: TWSAData;

    begin

    WSAStartup($101, WSAData);

    SockAddrIn.sin_addr.s_addr:= inet_addr(PChar(IPAddr));

    HostEnt:= gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);

    if HostEnt<>nil then result:=StrPas(Hostent^.h_name) else result:='';

    end;

    ◇[DELPHI]取得快捷方式中的连接

    function ExeFromLink(const linkname: string): string;

    var

    FDir,

    FName,

    ExeName: PChar;

    z: integer;

    begin

    ExeName:= StrAlloc(MAX_PATH);

    FName:= StrAlloc(MAX_PATH);

    FDir:= StrAlloc(MAX_PATH);

    StrPCopy(FName, ExtractFileName(linkname));

    StrPCopy(FDir, ExtractFilePath(linkname));

    z:= FindExecutable(FName, FDir, ExeName);

    if z > 32 then

    Result:= StrPas(ExeName)

    else

    Result:= '';

    StrDispose(FDir);

    StrDispose(FName);

    StrDispose(ExeName);

    end;

    ◇[DELPHI]控制TCombobox的自动完成

    {'Sorted' property of the TCombobox to true }

    var lastKey: Word; //全局变量

    //TCombobox的OnChange事件

    procedure TForm1.AutoCompleteChange(Sender: TObject);

    var

    SearchStr: string;

    retVal: integer;

    begin

    SearchStr := (Sender as TCombobox).Text;

    if lastKey <> VK_BACK then // backspace: VK_BACK or $08

    begin

    retVal := (Sender as TCombobox).Perform(CB_FINDSTRING, -1, LongInt(PChar(SearchStr)));

    if retVal > CB_Err then

    begin

    (Sender as TCombobox).ItemIndex := retVal;

    (Sender as TCombobox).SelStart := Length(SearchStr);

    (Sender as TCombobox).SelLength :=

    (Length((Sender as TCombobox).Text) - Length(SearchStr));

    end; // retVal > CB_Err

    end; // lastKey <> VK_BACK

    lastKey := 0; // reset lastKey

    end;

    //TCombobox的OnKeyDown事件

    procedure TForm1.AutoCompleteKeyDown(Sender: TObject; var Key: Word;

    Shift: TShiftState);

    begin

    lastKey := Key;

    end;

    ◇[DELPHI]如何清空一个目录

    function EmptyDirectory(TheDirectory :String ; Recursive : Boolean) :

    Boolean;

    var

    SearchRec : TSearchRec;

    Res : Integer;

    begin

    Result := False;

    TheDirectory := NormalDir(TheDirectory);

    Res := FindFirst(TheDirectory + '*.*', faAnyFile, SearchRec);

    try

    while Res = 0 do

    begin

    if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then

    begin

    if ((SearchRec.Attr and faDirectory) > 0) and Recursive

    then begin

    EmptyDirectory(TheDirectory + SearchRec.Name, True);

    RemoveDirectory(PChar(TheDirectory + SearchRec.Name));

    end

    else begin

    DeleteFile(PChar(TheDirectory + SearchRec.Name))

    end;

    end;

    Res := FindNext(SearchRec);

    end;

    Result := True;

    finally

    FindClose(SearchRec.FindHandle);

    end;

    end;

    ◇[DELPHI]如何计算一个目录的大小

    function GetDirectorySize(const ADirectory: string): Integer;

    var

    Dir: TSearchRec;

    Ret: integer;

    Path: string;

    begin

    Result := 0;

    Path := ExtractFilePath(ADirectory);

    Ret := Sysutils.FindFirst(ADirectory, faAnyFile, Dir);

    if Ret <> NO_ERROR then exit;

    try

    while ret=NO_ERROR do

    begin

    inc(Result, Dir.Size);

    if (Dir.Attr in [faDirectory]) and (Dir.Name[1] <> '.') then

    Inc(Result, GetDirectorySize(Path + Dir.Name + '\*.*'));

    Ret := Sysutils.FindNext(Dir);

    end;

    finally

    Sysutils.FindClose(Dir);

    end;

    end;

    ◇[DELPHI]截获WM_QUERYENDSESSION关机消息

    type

    TForm1 = class(TForm)

    procedure WMQueryEndSession(var Message: TWMQueryEndSession); message WM_QUERYENDSESSION;

    procedure CMEraseBkgnd(var Message:TWMEraseBkgnd);Message WM_ERASEBKGND;

    private

    { Private declarations }

    public

    { Public declarations }

    end;

    procedure TForm1.WMQueryEndSession(var Message: TWMQueryEndSession);

    begin

    Showmessage('computer is about to shut down');

    end;        

  • 相关阅读:
    实战,利用apache来做集群,实现负载均衡
    Paas
    mysql memcache
    JSP简单练习-定时刷新页面
    协定须要双工,可是绑定“WSHttpBinding”不支持它或者因配置不对而无法支持它
    ACM:图的BFS,走迷宫
    appium框架之bootstrap
    [JSP]JSP中include指令和include动作的差别
    cocos2d-x-3.1 win32程序-初识源代码(coco2d-x 学习笔记二)
    AT&amp;T汇编语言——简单实例及工具演示
  • 原文地址:https://www.cnblogs.com/karkash/p/2987998.html
Copyright © 2011-2022 走看看