Untitled Document
WIN -SHELL API APPLICATIONS
-Access User Names from Windows Login
-Add Directory Tree to Menu

-Controlling Form Resize
-Disable Screensaver while Application is Running

-How to Add Icons to Menus
-How to Retrieve Icon from a File's Associated Icon

-Loading Wav Files into Memory and Playing Them
-How to get the processor speed
-How can I change the system time?
-How can I immediately start the Windows screen saver?
-How do I change Window's desktop wallpaper?
-How do I hide my application from the Alt+Tab menu?
-How do I hide my application from the Windows Task Bar?
-How do I hide my application from the Windows Task List?
-How do I get a name of the CD-ROM drive?
-How do I search for files?
-How do I show/hide the windows taskbar?
-Tray Icon Application with no Form
-Unit for Determining Whether App is running inside of Delphi

-Clear Recent Docs On Exit
-Is Delphi running now?
-Moving a Form Without A Titlebar
-Open a Folder
-Start Files and applications from Delphi
-Show Dial-up dialog
-Change picture on the Start button
-Add an item to Recent Files

-Close window of another program
-Change system colors

-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;
var
Set_N_U_N : DbiUserName;
begin
if DbiGet_Net_U_N(Set_N_U_N) = DBIERR_NONE then
Result := StrPas(Set_N_U_N)
else
Result := '';
end;

Add Directory Tree to Menu

uses FileCtrl

Procedure Make_Tree_Menu(Menu_Item : TMenuItem;const stPathName : String);
var S_R : TSearchRec;
b_trv : Boolean;
New_Menu_Item : TMenuItem;
Begin
b_trv := (FindFirst(stPathName + '\*.*', faDirectory, S_R) = 0);
While (b_trv) Do
Begin
If (S_R.Name[1] <> '.') Then
Begin
If (DirectoryExists(stPathName + '\' + S_R.Name)) Then
Begin
New_Menu_Item := TMenuItem.Create(Menu_Item.Owner);
New_Menu_Item.Caption := S_R.Name;
Menu_Item.Add(New_Menu_Item);
Make_Tree_Menu(Menu_Item.Items[Menu_Item.Count - 1], stPathName + '\' + S_R.Name);
End;
End;
boTrouve := (FindNext(S_R) = 0);
End;
FindClose(S_R);
End;

Controlling Form Resize

Define this method of your form:
procedure WmGetMinMaxInfo(var PMSG: TWmGetMinMaxInfo);
message WM_GETMINMAXINFO;

procedure Form1.WmGetMinMaxInfo(var PMSG: TWmGetMinMaxInfo);
begin
with PMSG.MinMaxInfo^ do begin
PtMinTrackSize.X := Width;
PtMinTrackSize.Y := Height;
PtMaxTrackSize.X := Width;
PtMaxTrackSize.Y := Height;
end; {with}
end;

-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
procedure WMSysCommand( var Mes: TWMSysCommand); message WM_SYSCOMMAND;
then in the implementation,
procedure WMSysCommand( var Mes: TWMSysCommand);
begin
if Mes.cmdType = SC_ScreenSave then
Mes.Result := -1
else
Inherited;
end;

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);
var
i: Integer;
Menux: THandle;
begin
for i := 0 to 5 do
begin
Menux := GetMenuItemID(test.handle,i);
ModifyMenu(test.handle, Menux, MF_BYCOMMAND or MF_BITMAP, Menux,
PChar(image1.picture.bitmap.handle);
end;
end;

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
uses ShellAPI;
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
Hicon HICON;
iIcon: WORD;
begin
Hicon= ExtractAssociatedIcon(hInstance, 'C:\Windows\Win.ini', iIcon);
PostMessage(Handle, WM_SETICON, DWORD(False),Hicon);
end;

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
Wav_1: pointer;
Wav_2: pointer;

and then just do something like this:

procedure TForm1.Button2Click(Sender: TObject);

procedure Load_Wav_File(const Filename: string; var Ptr: pointer);
var
streaming_F: TFileStream;
F_Size: integer;
begin
streaming_F := TFileStream.Create(Filename, fmOpenRead);
GetMem(Ptr, streaming_F.F_Size);
streaming_F.ReadBuffer(Ptr^, streaming_F.F_Size);
streaming_F.Free;
end;
var
Wav_1,
Wav_2: pointer;
begin
Load_Wav_File('c:\win\media\chimes.wav', Wav_1);
Load_Wav_File('c:\win\media\chord.wav', Wav_2);
PlaySound(PChar(Wav_1), 0, SND_MEMORY or SND_NODEFAULT or SND_SYNC);
PlaySound(PChar(Wav_2), 0, SND_MEMORY or SND_NODEFAULT or SND_SYNC);
FreeMem(Wav_1);
FreeMem(Wav_2);
end;

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;
Application.ShowMainForm := False;
Application.CreateForm(TMainForm, MainForm);
ShowWindow(MainForm.Handle, SW_SHOWNORMAL);
Application.Run;

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
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation

{$R *.DFM}

{ The following functions are written for Delphi 1.x }
{ They should be easily adaptable for use with Delphi 2 & 3 }

function Extract_F_Name( FileName: string): string;
var p: integer;
begin { extracts the 8-character file name only }
Result := ExtractFileName(FileName);
p := pos('.',Result);
if p>0 then Result := Copy(Result,1,p-1);
end;

function IS_Delphi_Run: boolean;
begin { returns true if running within the IDE/compiler }
Result :=
(FindWindow('TApplication','Delphi') > 0) OR
(FindWindow('TPropertyInspector',nil) > 0) OR
(FindWindow('TAppBuilder',nil) > 0);
end;

function P_in_Delphi( EXEName: string ): boolean;
var handx: HWnd;
Storagex: array[0..80] of char;
Temp_St: string[80];
begin
Result := False;
if (IS_Delphi_Run) then
begin
EXEName := UpperCase(Extract_F_Name(EXEName));
handx := FindWindow('TAppBuilder',nil);
GetWindowText(handx, Storagex, SizeOf(Storagex)); { get window caption }
Temp_St := UpperCase(StrPas(Storagex));
Result := (Pos(EXEName,Temp_St) > 0) { does it contain EXEName ? }
and (Pos('RUNNING',Temp_St) > 0); { is it running ? }
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
if P_in_Delphi('Project1.Exe')
then Label1.Caption := 'TRUE'
else Label1.Caption := 'False';
end;

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
uses ShellApi;
...
ShellExecute(Handle, 'open','c:\Windows\notepad.exe', nil, nil, SW_SHOWNORMAL);

Open SomeText.txt with Notepad
ShellExecute(Handle,'open','c:\windows\notepad.exe','c:\SomeText.txt',nil, SW_SHOWNORMAL);

Display the contents of the "DelphiDownload" folder
ShellExecute(Handle,'open','c:\DelphiDownload',nil, nil, SW_SHOWNORMAL);

Execute a file according to its extension
ShellExecute(Handle, 'open','c:\MyDocuments\Letter.doc',nil,nil,SW_SHOWNORMAL);

Open web site or a *.htm file with the default web explorer
ShellExecute(Handle, 'open','http://delphi.about.com',nil,nil, SW_SHOWNORMAL);

Send an e-mail with the subject and the message body
var
em_subject, em_body, em_mail : string;
begin
em_subject := 'How are you';
em_body := 'I write my letter here....';

em_mail := 'mailto:deryart@yahoo.com?subject=' +em_subject + '&body=' + em_body ;
ShellExecute(Handle,'open',PChar(em_mail), nil, nil, SW_SHOWNORMAL);
end;

Execute a program and wait until it has finished. The following example uses the ShellExecuteEx API function.
// Execute the Windows Calculator and pop up
// a message when the Calc is terminated.

uses ShellApi;
...
var
S_inf: TShellExecuteInfo;
Exit_Code: DWORD;
File_Executed, Params_String, start_in_str: string;
begin
File_Executed:='c:\Windows\Calc.exe';
FillChar(S_inf, SizeOf(S_inf), 0);
S_inf.cbSize := SizeOf(TShellExecuteInfo);
with S_inf do begin
fMask := SEE_MASK_NOCLOSEPROCESS;
Wnd := Application.Handle;
lpFile := PChar(File_Executed);
{Params_String can contain the application parameters.}
// lpParameters := PChar(Params_String);
{start_in_str specifies the name of the working directory. If ommited, the current directory is used.}
// lpDirectory := PChar(start_in_str);

nShow := SW_SHOWNORMAL;
end;
if ShellExecuteEx(@S_inf) then begin
repeat
Application.ProcessMessages;
GetExit_CodeProcess(S_inf.hProcess, Exit_Code);
until (Exit_Code <> STILL_ACTIVE) or
Application.Terminated;
ShowMessage('Calculator terminated');
end
else ShowMessage('Error starting Calc!');
end;

WinExec
If you are working with Windows 3.xx and 16 bit applications use the WinExec function, like:
// run Notepad
WinExec('c:\windows\NOTEPAD.EXE', SW_SHOWNORMAL);
// run Notepad and display SomeText.txt
WinExec('c:\windows\NOTEPAD.EXE C:\SomeText.txt',
SW_SHOWNORMAL);
// execute a DOS DIR command
WinExec('COMMAND.COM /C DIR *.*', SW_SHOWNORMAL);

Show Dial-up dialog
Add WinInet to USES

InternetAutodial(0, 0);
If you put 2 to the first param, dialog starts autamatically dialing.

Change picture on the Start button
var
Form1: TForm1;
Butn: hWnd;
Old_bitmap: THandle;
New_Image: TPicture;

procedure TForm1.FormCreate(Sender: TObject);
begin
New_Image := TPicture.create;
New_Image.LoadFromFile('C:\Windows\Circles.BMP');
Butn := FindWindowEx (FindWindow('Shell_TrayWnd', nil), 0,'Button', nil);
Old_bitmap := SendMessage(Butn,
BM_SetImage, 0,
New_Image.Bitmap.Handle);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
SendMessage(Butn,BM_SetImage,0,Old_bitmap);
New_Image.Free;
end;

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;
RGB_Color:TRGBTriple;
begin
Color:=COLOR_ACTIVECAPTION;
RGB_Color.rgbtBlue:=128;//Red
RGB_Color.rgbtGreen:=0;//Green
RGB_Color.rgbtRed:=0;//Blue
SetSysColors(1,Color,RGB_Color);
end;
Note: Order of color is by TRGBTriple reversed

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;
Description_X,IconPath: String;IconIdex: Integer);

var
My_obj : IUnknown;
My_Linx : IShellLink;
My_Persist : IPersistFile;
begin
My_obj := CreateComObject(CLSID_ShellLink);
My_Linx := My_obj as IShellLink;
My_Persist := My_obj as IPersistFile;
with My_Linx do
begin
SetArguments (PChar(Arguments));
SetPath (PChar(File_Name));
SetWork_Dir(PChar(Work_Dir));
SetDescription_X (PChar(Description_X));
SetIconLocation (PChar(IconPath), IconIdex);
end;
If Not DirectoryExists(ExtractFileDir(Target_Link_File)) then
CreateDir(ExtractFileDir(Target_Link_File));
My_Persist.Save(PWChar(Target_Link_File),False);
My_Linx := Nil;
My_Persist := Nil;
My_obj := Nil;
end;
Then call procedure, for example:
Create_A_Linx('C:\Win98', 'C:\Win98\Sndrec32.exe','', 'C:\Win98\sndrec32.lnk', 'SndRec', 'C:\icon.ico', 0)

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);
begin
AddFontResource('XXXFont.TTF');
SendMessage(HWND_BROADCAST,WM_FONTCHANGE,0,0);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
RemoveFontResource('XXXFont.TTF');
SendMessage(HWND_BROADCAST,WM_FONTCHANGE,0,0);
end;

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
begin
mciSendString('Set cdaudio door closed wait', nil, 0, handle);
end;

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;
var H, H2, Explorer_frame: HWND;
begin
Explorer_frame:=FindWindow('Explorer_frame', nil);
H2:=FindWindowEX(Explorer_frame, 0, 'WorkerA', nil);
H:=FindWindowEX(H2, 0, 'ReBarWindow32', nil);
H2:=FindWindowEX(H, 0, 'ComboBoxEx32', nil);
H:=FindWindowEX(H2, 0, 'Combobox', nil);
H2:=FindWindowEX(H, 0, 'Edit', nil);
if H2 = 0 then
begin
Result:=False;
Exit;
end;
SendMessage(H2, WM_SETTEXT, Length(URL_string), LongInt(URL_string));
SendMessage(H2, WM_KEYDOWN, 13, 0);
if ToFront then
SetForegroundWindow(Explorer_frame);
Result:=True;
end;

Sample call:
Set_Explr_URL('http://psod.3web.cz', True);

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
procedure Show_Task_Bar;
var
hTaskBar:THandle;
begin
hTaskBar:=FindWindow('Shell_TrayWnd',Nil);
ShowWindow(hTaskBar,Sw_Normal);
end;

Shutoff windows
SetSystemPowerState(True, True);
Terminate running process

procedure TForm1.Button2Click(Sender: TObject);
var
Ret: BOOL;
Pr_ID: integer; //process identifier
Pr_Handle: THandle; //process handle

begin
with ListView1 do
begin
Pr_ID:=StrToInt(ItemFocused.SubItems[1]);
Pr_Handle:=OpenProcess(1, BOOL(0), Pr_ID);
Ret:=TerminateProcess(Pr_Handle, 0);
if Integer(Ret) = 0 then
MessageDlg('Couldn''t close' + ItemFocused.Caption, mtInformation, [mbOk], 0)
else
ItemFocused.Delete;
end;
end;

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:
function SHFindFiles(pidlRoot: PItemIDList; pidlSavedSearch: PItemIDList): Boolean;
stdcall; external 'Shell32.dll' index 90;

Example:
SHFindFiles(nil, nil);

Show Restart Windows dialog
Declaration:

function RestartDialog(ParentWnd: HWND; Reason: PAnsiChar;
Flags: LongInt): LongInt; stdcall; external 'Shell32.dll' index 59;

Example:
if RestartDialog(0, 'I''m restart dialog' + #13 + #13, EW_RESTARTWINDOWS) = IDYES then
ShowMessage('Succesfully started.');

Different possibilities for Flags:
EWX_LOGOFF
EWX_SHUTDOWN
EWX_REBOOT
EW_RESTARTWINDOWS
EW_REBOOTSYSTEM
EW_EXITANDEXECAPP

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:
procedure TForm1.Button1Click(Sender: TObject);
begin
if Opendialog1.Execute then Show_P_Dialog(Opendialog1.FileName);
end;

Show the Find Dialog
Add DDEMan to USES clause

procedure Show_F_Dialog(Folderx:String);
begin
with TDDEClientConv.Create(Self) do
begin
ConnectMode := ddeManual;
ServiceApplication := 'Explorer.exe';
SetLink('Folders', 'AppProperties');
OpenLink;
ExecuteMacro(PChar('[FindFolder(, ' + Folderx+ ')]'), False);
CloseLink;
Free;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
Show_F_Dialog('C:\Windows');
end;

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;
begin
Tick_Count := GetTickCount;
repeat
//If you wish to don't stop the program, put here this
Application.ProcessMessages;
until GetTickCount - Tick_Count >= 2000;//milliseconds count
Beep;
end;

Show Select icon dialog
Add ShellApi to USES

Declaration:
function PickIconDlgA(OwnerWnd: HWND; lpstrFile: PAnsiChar; var nMaxFile: LongInt;
var lpdwIconIndex: LongInt): LongBool; stdcall; external 'SHELL32.DLL' index 62;

Example (changes application icon):
var
File_name: String;
Size, Index: LongInt;
begin
Size := MAX_PATH;
File_name := 'Shell32.dll';
if PickIconDlgA(0, PChar(File_name), Size, Index) then
begin
if Index <> -1 then
Application.Icon.Handle := ExtractIcon(hInstance, PChar(FileName), Index);
end;
end;

Using the Registry With Delphi
Add "registery" to Uses clause

type
TForm1 = class(TForm)
Edit1: TEdit;
btnRead: TButton;
btnWrite: TButton;
private
My_sample_reg: TRegistry;
public
{ Public declarations }
end;
To Write some information into registery

procedure TForm1.btnWriteClick(Sender: TObject);
begin
try
My_sample_reg := TRegistry.Create;
My_sample_reg.RootKey := HKEY_LOCAL_MACHINE;
if My_sample_reg.OpenKey('SOFTWARE\myApp\', TRUE) then
begin
My_sample_reg.WriteString('My Name', Edit1.Text);
My_sample_reg.WriteInteger('Top', Form1.Top);
My_sample_reg.WriteInteger('Left', Form1.Left);
end;
finally
My_sample_reg.Free;
end;
end;

Open up the "btnReadClick" procedure of your code window. Enter in the following code:

procedure TForm1.btnReadClick(Sender: TObject);
begin
try
My_sample_reg := TRegistry.Create;
My_sample_reg.RootKey := HKEY_LOCAL_MACHINE;
if My_sample_reg.OpenKey('SOFTWARE\myApp', FALSE) then
begin
Edit1.Text := My_sample_reg.ReadString('App Name');
Form1.Top := My_sample_reg.ReadInteger('Top');
Form1.Left := My_sample_reg.ReadInteger('Left');
end;
finally
My_sample_reg.Free;
end;
end;

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;
var
DeviceMode: TDeviceMode;
begin
with DeviceMode do begin
dmSize := SizeOf(TDeviceMode);
dmPelsWidth := Width;
dmPelsHeight := Height;
dmFields := DM_PELSWIDTH or DM_PELSHEIGHT;
end;
Result := ChangeDisplaySettings(DeviceMode, CDS_UPDATEREGISTRY);
end;

procedure TForm1.Button4Click(Sender: TObject);
var
OldWidth, OldHeight: integer;
begin
OldWidth := GetSystemMetrics(SM_CXSCREEN); // Get original screen resolation
OldHeight := GetSystemMetrics(SM_CYSCREEN);
Setscreenresolution(640,480);
end;

Correct resolation again:
setScreenResolation(OldWitdh,OldHeight);

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
procedure TForm1.Button1Click(Sender: TObject);
var
hwndHandle : THANDLE;
hMenuHandle : HMENU;
begin
hwndHandle := FindWindow(nil, 'Untitled - Notepad');
if (hwndHandle <> 0) then begin
hMenuHandle := GetSystemMenu(hwndHandle, FALSE);
if (hMenuHandle <> 0) then
DeleteMenu(hMenuHandle, SC_CLOSE, MF_BYCOMMAND);
end;
end;

This procedure closes notepad

procedure TForm1.Button2Click(Sender: TObject);
begin
PostMessage(FindWindow(Nil, 'Untitled - Notepad'), WM_QUIT, 0, 0);
end;

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);
begin
if IsUserOnline then showmessage('On the net') Else
ShowMessage('Not connected');
end;

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;
 
 
 
 


Delphi Home Page
DK Home Page

Saturday, August 10, 2002 8:51 PM