-Create shortcut (lnk, pif)
-Detect insertion of audio CD
-Get second gradient color of caption
-Install and uninstall font
-Open and close CD-ROM
-Play wav file
-Show Find computer dialog
-Set URL of IE
-Show\hide taskbar
-Shutoff windows
-Terminate running process
-Window without caption but with border
-Run an app and wait until it finishes
-Show Find files dialog
-Show Restart Windows dialog
-Show the File Properties Dialog
-Show the Find Dialog
-Download a file
-Procedure delay
-Show Select icon dialog
-Using the Registry With Delphi
-Change Walpaper
-Animated Window
-Change System resulation
-Clear CMOS Memory
-Close an Application
-Test your dial-up connection
-System Calls
-Read registery and Get system info
Access User Names from Windows Login | |
function Get_Net_U_N:
string; const Net_U_N_Len: integer = 50; begin SetLength(result, Net_U_N_Len); Get_U_N(pChar(result), Net_U_N_Len); SetLength(result, StrLen(pChar(result))); end; function Get_U_N : string; |
|
Add Directory Tree to Menu | |
uses FileCtrl Procedure Make_Tree_Menu(Menu_Item : TMenuItem;const
stPathName : String); |
|
Controlling Form Resize | |
Define this method of your form: procedure Form1.WmGetMinMaxInfo(var PMSG: TWmGetMinMaxInfo); |
|
-Disable Screensaver while Application is Running | |
Yes, there
is. It uses the WM_SYSCOMMAND message, with a cmdType of SC_ScreenSave.
So, in your main forms Interface section, declare a procedure to handle
the WM_SYSCOMMAND message, like this:
private |
|
How to Add Icons to Menus | |
Put a MainMenu-component,
an Image(put a Bitmap into it) and a Button on a new form and create a
menu named Test and six menuitems (dummies). So now the code:
procedure TForm1.ButtonClick(Sender: TObject); |
|
How to Retrieve Icon from a File's Associated Icon | |
Here's
a code snippet. Clicking Button1 will change the form's icon to the associated
icon of "C:\Windows\Win.ini" (usually like a notepad icon).
implementation |
|
Loading Wav Files into Memory and Playing Them | |
You'll
need to add MMSystem to your uses clause. You can find the description
of "PlaySound" in the MM.hlp file in your \Delphi\Help directory.
It isn't linked into the standard help system index, so searching for
it won't work (but Ctrl-F1 in the editor will).
private and then just do something like this: procedure TForm1.Button2Click(Sender: TObject); procedure Load_Wav_File(const Filename: string;
var Ptr: pointer); |
|
How to get the processor speed | |
function Get_Speed: Double;
const Delay_time = 500; var TimerHi, TimerLo: DWORD; Pr_Class, Pr: Integer; begin Pr_Class := GetPriorityClass(GetCurrentProcess); Pr := GetThreadPriority(GetCurrentThread); SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS); SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL); Sleep(10); asm dw 310Fh mov TimerLo, eax mov TimerHi, edx end; Sleep(Delay_time); asm dw 310Fh sub eax, TimerLo sbb edx, TimerHi mov TimerLo, eax mov TimerHi, edx end; SetThreadPriority(GetCurrentThread, Pr); SetPriorityClass(GetCurrentProcess, Pr_Class); Result := TimerLo / (1000.0 * Delay_time); end; //To use this function, write: Caption:=Format('%f MHz', [Get_Speed]); |
|
How can I change the system time? | |
procedure TForm1.Button1Click(Sender:
TObject); var S_Time : TSystemTime; begin S_Time.wYear := 2000; S_Time.wMonth := 5; S_Time.wDay := 23; S_Time.wHour := 23; S_Time.wMinute := 20; S_Time.wSecond := 0; S_Time.wMilliSeconds := 0; SetLocalTime(S_Time); end; |
|
How can I immediately start the Windows screen saver? | |
SendMessage(GetDesktopWindow, WM_SYSCOMMAND, SC_SCREENSAVE, 0) | |
How do I change Window's desktop wallpaper? | |
Call SystemParametersInfo and pass
the SPI_SETDESKWALLPAPER parameter along with the filename of the new
bitmap to use. Example: SystemParametersInfo(SPI_SETDESKWALLPAPER,0,PChar('C:\SomeBitMap.BMP'), SPIF_SENDWININICHANGE); |
|
How do I hide my application from the Alt+Tab menu? | |
ShowWindow(Application.Handle, SW_HIDE); SetWindowLong(Application.Handle, GWL_EXSTYLE, GetWindowLong(Application.Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW and not WS_EX_APPWINDOW); |
|
How do I hide my application from the Windows Task Bar? | |
In the project's source code (Project -> View Source) add Windows to the uses clause. After it says "Application.Initialize;" type "Application.ShowMainForm := False;" then add "ShowWindow(Application.Handle, SW_HIDE);" just before "Application.Run;". Now in each unit that uses a form, just add "ShowWindow(Application.Handle, SW_HIDE);" to the initialization section. | |
How do I hide my application from the Windows Task List? | |
SetWindowLong(Application.Handle,GWL_EXSTYLE,
GetWindowLong(Application.Handle,GWL_EXSTYLE) or WS_EX_TOOLWINDOW and not WS_EX_APPWINDOW); |
|
How do I get a name of the CD-ROM drive? | |
function CD_Drv: Char; var DRV_mp, Msk: DWORD; I_c: Integer; Root_drv: String; begin Result := #0; Root_drv := 'A:\'; DRV_mp := GetLogicalDrives; Msk := 1; for I_c:= 1 to 32 do begin if (Msk and DRV_mp) <> 0 then if GetDriveType(PChar(Root_drv)) = DRIVE_CDROM then begin Result := Root_drv[1]; Break; end; Msk := Msk shl 1; Inc(Root_drv[1]); end; end; |
|
How do I search for files? | |
The
function below will return a TStringList of matches for a search string.
function Find_File(Path, Mask: string; FileAttrs : Integer) :TStringList; var S_rec : TSearchrec; begin {Set Path to the folder name. Set mask to the mask you want, for example '*.exe'. For information on the FileAttrs parameter, lookup the FindFirst function in Delphi Help.} Result := TStringList.Create; if FindFirst(Path+Mask, FileAttrs, S_rec) = 0 then try Result.Add(S_rec.Name); while FindNext(S_rec) = 0 do Result.Add(S_rec.Name); finally FindClose(S_rec); end; end; |
|
How do I show/hide the windows taskbar? | |
procedure Hide_Task_bar; var Wn_Hand : THandle; Wn_Class : array[0..50] of Char; begin StrPCopy(@Wn_Class[0], 'Shell_TrayWnd'); Wn_Hand := FindWindow(@Wn_Class[0], nil); ShowWindow(Wn_Hand, SW_HIDE); {This hides the taskbar} end; procedure Show_Task_Bar; var Wn_Hand : THandle; Wn_Class : array[0..50] of Char; begin StrPCopy(@Wn_Class[0], 'Shell_TrayWnd'); Wn_Hand := FindWindow(@Wn_Class[0], nil); ShowWindow(Wn_Hand, SW_RESTORE); {This restores the taskbar} end; |
|
Tray Icon Application with no Form | |
The
tightest, no-flicker method I've found is:
Application.Initialize; Your main form then is opened as expected as the foreground window, no icon on the taskbar and no flicker. From here you should be able to either use a TrayIcon component or code the tray icon functionality yourself. |
|
Unit for Determining Whether App is running inside of Delphi | |
unit Unit1; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type var {$R *.DFM} { The following functions
are written for Delphi 1.x } function Extract_F_Name( FileName: string): string; function IS_Delphi_Run: boolean; function P_in_Delphi( EXEName: string ): boolean; procedure TForm1.Button1Click(Sender: TObject); |
|
Clear Recent Docs On Exit | |
//Add Registry
to USES uses Registry, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; procedure TForm1.Button1Click(Sender: TObject); var F_Storage : array [0..3] of byte; My_Reg : TRegistry; begin //Clear Recent Docs On Exit F_Storage[0]:=1; F_Storage[1]:=0; F_Storage[2]:=0; F_Storage[3]:=0; ////No Clear Recent Docs On Exit //F_Storage[0]:=0; //F_Storage[1]:=0; //F_Storage[2]:=0; //F_Storage[3]:=0; My_Reg:=TRegistry.Create; My_Reg.RootKey:=HKEY_CURRENT_USER; My_Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Policies\Explorer',True); My_Reg.WriteBinaryData('ClearRecentDocsOnExit',F_Storage,4); My_Reg.CloseKey; My_Reg.Free; //You Need Restart Windows end; |
|
Is Delphi running now? | |
function Is_Delphi_Running_Now : boolean;
begin Result:= FindWindow('TAppBuilder', nil) > 0); end; This function will return a value of TRUE if the IDE is running or FALSE, otherwise. |
|
Moving a Form Without A Titlebar | |
ReleaseCapture; SendMessage(Form1.Handle, WM_SYSCOMMAND, 61458, 0); | |
Open a Folder | |
Uses shellapi procedure TForm1.Button1Click(Sender: TObject); begin ShellExecute(handle, 'Open', 'C:\PlanetSourceCode', nil, nil, SW_SHOWNORMAL); end; |
|
Start Files and applications from Delphi | |
Run Notepad Open SomeText.txt with
Notepad Display the contents of the "DelphiDownload"
folder Execute a file according to its extension
Open web site or a *.htm file with the default
web explorer Send an e-mail with the subject and the message
body Execute a program and wait until it has finished.
The following example uses the ShellExecuteEx API function. WinExec
|
|
Show Dial-up dialog | |
Add WinInet to USES
InternetAutodial(0, 0); |
|
Change picture on the Start button | |
var Form1: TForm1; Butn: hWnd; Old_bitmap: THandle; New_Image: TPicture; procedure TForm1.FormCreate(Sender: TObject);
procedure TForm1.FormDestroy(Sender: TObject); |
|
Add an item to Recent Files | |
Add ShlOBJ, ShellAPI
to USES procedure StartDocumentsMenu(File_Path : string); begin SHAddToRecentDocs(SHARD_PATH,PChar(File_Path)); end; Now write StartDocumentsMenu('C:\Readme.txt') to add file C:\Readme.txt to Recent Files |
|
Close window of another program | |
PostMessage(FindWindow(Nil,'Derya'),WM_QUIT,0,0); | |
Change system colors | |
This
code changes caption color to dark red:
var Color:Integer; |
|
Create shortcut (lnk, pif) | |
Add FileCtrl,ShlObj,
ActiveX, ComObj to USES
procedure Create_A_Linx(Work_Dir,File_Name,Arguments:
String;Target_Link_File: WideString; |
|
Detect insertion of audio CD | |
function LookForAudioCd(Drive : Char)
: Boolean; var Drive_path : String; Max_Comp_Path : DWORD; Sys_Flags : DWORD; Vol_Name : String; OldErrorMode: UINT; Drive_Type: UINT; begin Result := False; Drive_path := Drive + ':\'; OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); Drive_Type := GetDrive_Type(Pchar(Drive_path)); SetErrorMode(OldErrorMode); if Drive_Type <> DRIVE_CDROM then Exit; SetLength(Vol_Name, 64); GetVolumeInformation(PChar(Drive_path), PChar(Vol_Name), Length(Vol_Name), nil, Max_Comp_Path, Sys_Flags, nil, 0); if lStrCmp(PChar(Vol_Name), 'Audio CD') = 0 then Result := True; end; procedure TForm1.Button1Click(Sender: TObject); begin if LookForAudioCd('J') then begin ShowMessage('In drive J is an audio CD.'); end else begin ShowMessage('No audio CD found in drive J.'); end; end; |
|
Get second gradient color of caption | |
const clActiveCaptionGradient: TColor = clActiveCaption; clInactiveCaptionGradient: TColor = clInactiveCaption; var UseGradient: Boolean; begin // Find out if gradient caption is enabled if (SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, @UseGradient, 0)) then begin if (UseGradient) then begin clActiveCaptionGradient := GetSysColor(COLOR_GRADIENTACTIVECAPTION); clInactiveCaptionGradient := GetSysColor(COLOR_GRADIENTINACTIVECAPTION); end; end; Panel1.Color:=clActiveCaptionGradient; Panel2.Color:=clInactiveCaptionGradient; end; |
|
Install and uninstall font | |
procedure TForm1.FormCreate(Sender: TObject);
procedure TForm1.FormDestroy(Sender: TObject);
|
|
Open and close CD-ROM | |
Add MMSystem to USES Open CD-ROM: begin mciSendString('Set cdaudio door open', nil, 0, hinstance); end; Close CD-ROM |
|
Play wav file | |
Add
MMSystem to USES
PlaySound('c:\Gorilla.wav', 0, SND_FILENAME + SND_ASYNC); |
|
Show Find computer dialog | |
Add ShlObj to USES: function SHFindComputer(pidlRoot: PItemIDList; pidlSavedSearch: PItemIDList): Boolean; stdcall; external 'Shell32.dll' index 91; Example: SHFindComputer(nil, nil); |
|
Set URL of IE | |
Address changes only
in last opened window.
function Set_Explr_URL(URL_string: String; ToFront:
Boolean): HWND; Sample call: |
|
Show\hide taskbar | |
1)Hide procedure Hide_Task_bar; var hTaskBar:THandle; begin hTaskBar:=FindWindow('Shell_TrayWnd',Nil); ShowWindow(hTaskBar,Sw_Hide); end; 2)Show |
|
Shutoff windows | |
SetSystemPowerState(True, True); | |
Terminate running process | |
procedure TForm1.Button2Click(Sender: TObject); |
|
Window without caption but with border, | |
SetWindowLong (Handle, GWL_STYLE,
GetWindowLong (Handle, GWL_STYLE) AND NOT WS_CAPTION); ClientHeight:=Height; |
|
Run an app and wait until it finishes | |
procedure TForm1.Button1Click(Sender:
TObject); var Pr_inf: TProcessInformation; St_inf: TStartupInfo; begin FillChar(Pr_inf, sizeof(TProcessInformation), 0); FillChar(St_inf, sizeof(TStartupInfo), 0); St_inf.cb := sizeof(TStartupInfo); if CreateProcess('C:\Win98\notepad.exe', nil, nil, nil, false, NORMAL_PRIORITY_CLASS, nil, nil, St_inf, Pr_inf) <> False then begin WaitForSingleObject(Pr_inf.hProcess, INFINITE); CloseHandle(Pr_inf.hProcess); Application.MessageBox('Notepad finished','Info', MB_ICONINFORMATION); end else Application.MessageBox('Application couldn''t be executed', 'Error', MB_ICONEXCLAMATION); end; |
|
Show Find files dialog | |
Add ShlObj to USES
Declaration: Example: |
|
Show Restart Windows dialog | |
Declaration:
function RestartDialog(ParentWnd: HWND; Reason:
PAnsiChar; Example: Different possibilities for Flags: |
|
Show the File Properties Dialog | |
Add ShellApi to USES
clause procedure Show_P_Dialog(FileName:String); var S_Ex_Info: TShellExecuteInfo; begin FillChar(S_Ex_Info, SizeOf(S_Ex_Info), 0); S_Ex_Info.cbSize := SizeOf(S_Ex_Info); S_Ex_Info.lpFile := PChar(filename); S_Ex_Info.lpVerb := 'properties'; S_Ex_Info.fMask := SEE_MASK_INVOKEIDLIST; ShellExecuteEx(@S_Ex_Info); end; How to use: |
|
Show the Find Dialog | |
Add DDEMan to USES
clause
procedure Show_F_Dialog(Folderx:String); procedure TForm1.Button1Click(Sender: TObject);
|
|
Download a file | |
Add
URLMon to USES URLDownloadToFile(nil, 'http:/www.deryart.freeservers.com/magic.rar', 'C:\magic.rar', 0, nil); This function downloads component TSuperCombo to C:\magic.rar |
|
Procedure delay | |
You cerainly
know Delay procedure from Pascal, but that isn't in Delphi. Instead of Delay is Sleep(). But if you use Sleep(), program stops to react. With this code, it won't happen. var Tick_Count: Cardinal; |
|
Show Select icon dialog | |
Add ShellApi to USES
Declaration: Example (changes application icon): |
|
Using the Registry With Delphi | |
Add "registery"
to Uses clause
type procedure TForm1.btnWriteClick(Sender: TObject); procedure TForm1.btnReadClick(Sender: TObject); |
|
Change Walpaper | |
procedure ChangeWallpaper(bitmap:
string); {bitmap contains filename: *.bmp} var pBitmap : pchar; begin bitmap:=bitmap+#0; pBitmap:=@bitmap[1]; SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, pBitmap, SPIF_UPDATEINIFILE); end; Example: ChangeWallpaper('c:\winnt\circles.bmp'); |
|
Animated Window | |
procedure TForm1.Button1Click(Sender:
TObject); begin AnimateWindow(Form1.Handle, 1000, AW_HOR_POSITIVE or AW_HOR_NEGATIVE or AW_Hide); AnimateWindow(Form1.Handle, 1000, AW_HOR_POSITIVE or AW_HOR_NEGATIVE or AW_CENTER); AnimateWindow(Form1.Handle, 1000, AW_HOR_NEGATIVE or AW_HOR_POSITIVE or AW_Hide); AnimateWindow(Form1.Handle, 1000, AW_HOR_POSITIVE or AW_HOR_NEGATIVE or AW_SLIDE); AnimateWindow(Form1.Handle, 1000, AW_VER_POSITIVE or AW_HIde); AnimateWindow(Form1.Handle, 1000, AW_VER_NEGATIVE or AW_SLIDE); end; |
|
Change System resulation | |
function SetScreenResolution(Width, Height: integer):
Longint; procedure TForm1.Button4Click(Sender: TObject); Correct resolation again: |
|
Clear CMOS Memory | |
procedure TForm1.Button1Click(Sender:
TObject); label label0; var a:integer; begin a:=MessageDlg('This operation cannot be undone, Continue ?', mtConfirmation,mbOkCancel, 0); if a=2 then exit; beep; asm mov ax,$3f00 xor bl,bl label0: mov al,bl out $70,al mov al,$ff out $71,al inc bl dec ah jnz label0 end; //Asm showMessage('CMOS Memory Cleared !'); application.terminate; end; |
|
Close an Application | |
Closes Notepad menu This procedure closes notepad procedure TForm1.Button2Click(Sender: TObject); |
|
Test your dial-up connection | |
Use
Wininet function IsUserOnline:boolean; var connect_status:dword; begin connect_status := 2 {user uses a lan} + 1 {user uses a modem.} + 4 {user uses a proxy} ; result := InternetGetConnectedState(@connect_status,0); end; procedure TForm1.Button1Click(Sender: TObject); |
|
System Calls | |
Disable Screensaver SendMessage(Handle,WM_SYSCOMMAND,SC_SCREENSAVE,0); Enable ScreenSaver SendMessage(Handle,WM_SYSCOMMAND,SC_SCREENSAVE,1); Monitor off SendMessage(Handle,WM_SYSCOMMAND,SC_MONITORPOWER,0); Monitor on SendMessage(Handle,WM_SYSCOMMAND,SC_MONITORPOWER,1); Form size SendMessage(Handle,WM_SYSCOMMAND,SC_SIZE,1); move window SendMessage(Handle,WM_SYSCOMMAND,SC_MOVE,0); Zoom window SendMessage(Handle,WM_SYSCOMMAND,SC_ZOOM, 1); window separator SendMessage(Handle,WM_SYSCOMMAND,SC_SEPARATOR, 1); Open start menu SendMessage(Handle,WM_SYSCOMMAND,SC_TASKLIST,1); |
|
Read registery and Get system info | |
Use Registery in USES
procedure TRegOrganization.Button1Click(Sender: TObject); var reg : TRegistry; Buff : String; begin reg := TRegistry.Create; reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\',True) then begin //To Find Out How I Knew What Was What To Get This Info Click on Start Run Then Type Regedit then under local key microsoft\windows\currentversion you can see it in the registry WinVersionTxt.Text := reg.ReadString('Version'); WinVersionNumberTxt.Text := Reg.ReadString('VersionNumber'); WinProductKeyTxt.Text := Reg.ReadString('ProductKey'); RegOwnerTxt.Text := Reg.ReadString('RegisteredOwner'); RegOrganizationTxt.Text := Reg.ReadString('RegisteredOrganization'); ProduckIdTxt.Text := Reg.ReadString('ProductId'); end; reg.CloseKey; reg.Free; end; |
|
|