Ads 468x60px

Smaller time frame always follow the bigger time frame. It's better wait be patience to enter in position than risk with BIG SL. Having strong trading discipline and taking losses when necessary is a sign of serious trading approach

Tuesday, August 14, 2012

turn on/off my monitors


I have successfully tested this on Windows XP and Windows 7:
const
  MONITOR_ON      = -1;
  MONITOR_OFF     =  2;
  MONITOR_STANDBY =  1;
To turn off the monitor:
  SendMessage(Application.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);
To turn on the monitor:
  SendMessage(Application.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_ON);


comments

Saturday, August 11, 2012

WINDOWS SERVICES - CONVERTING BETWEEN KEY AND DISPLAY NAMES


We've demonstrated how to check the status of Windows services and how to control them. One element missing from those functions was a way to convert between key and display names of Windows services. 
 
That's right, a Windows service has two names. The long name you see in the Control Panel is the display name of the service. The internal shorter name of the serivce is called the key name. Most functions require that you use the key name of a service, so here's a function to convert a display name to a key name. comments

WINDOWS SERVICES - GETTING A LIST OF INSTALLED SERVICES


Want to get a list of active, inactive or all Windows services? Following function can help you to do this, but be sure to read other Windows services related tips for details. 
 
const
  //
  // Service Types
  //
  SERVICE_KERNEL_DRIVER       = $00000001;
  SERVICE_FILE_SYSTEM_DRIVER  = $00000002;
  SERVICE_ADAPTER             = $00000004;
  SERVICE_RECOGNIZER_DRIVER   = $00000008;
comments

BIN2HEX - SCRIPT TO CONVERT DATA FILES INTO SOURCE CODE ARRAYS


Looking for a way to convert a binary (or even a text) file into a Perl, Pascal/Delphi, C/C++, or Java source code array? For example, you may want to do this to include a GIF or other binary file directly inside your Perl CGI script, rather than reading the data from a file to reduce file access. If you're writing Windows programs, you could use the same method to store resource files in your executable files. 
 
The bin2hex.pl script will take a binary file name and output a source code array, in the specified language, necessary to recreate the input data inside a program.
 
To run the script, first make sure that you have a Perl interpreter installed on your system and download the bin2hex.pl script. Then execute the following command from your command prompt (assuming you want to convert a file named banner.gif to a Perl string):
 
comments

CALLING CONTROL PANEL APPLETS FROM YOUR PROGRAMS AND SCRIPTS


Looking for a way to open Control Panel applets from your programs without opening the Control Panel
 
Whether you want your users to change the system date/time properties, add a new modem or change joystick settings, there's an easy way to call all such Control Panel applets (icons) without opening the Control Panel folder. The good news is that you can use this method in any Windows programming environment or even in a simple BATch file.
 
Running the following command from your program will do the trick (CPL being the file name of the Control Panel applet to open. a list of such applets can be found at the bottom of this document):
 
comments

IS WINDOWS TASKBAR'S AUTO HIDE FEATURE ENABLED?


Want to know if the Windows taskbar's auto hide feature is enabled? Here's a simple function to check this written in C Language / C++ and Delphi. 
 
Delphi CODE
 
uses ShellAPI;

(*
  Returns TRUE if taskbar auto hide is on.

  if(IsTaskBarautoHideOn)then
  begin
    // auto hide is ON
  end;
comments

EASY WAY TO COMPARE DATES


Did you know that you can easily compare dates by using the "EncodeDate()"? Here are some examples: 
 
uses
  SysUtils;

{...}

if(Date > EncodeDate( 1997, 1, 1 ))then
begin
  { display "this program has expired" }
end;

{...}

if( EncodeDate( 1997, 1, 1 )
  > EncodeDate( 1996, 1, 1 ) ) then
begin
  {...}
end;
Listing #1 : Delphi code. Download datecomp (0.27 KB).

comments

ADD PERSONALITY TO YOUR GOOD OLD MKDIR() FUNCTION...


Looking for a function that can create multiple directories (directories inside directories) using a single function call? Well, "MkDir()" function is not it, but the following function maybe just what you're looking for: 
 
program MkDirMul;

uses
  SysUtils, FileCtrl;

procedure MkDirMulti(sPath : string);
begin
  if('' = sPath[Length(sPath)])then
  begin
    sPath := Copy(sPath, 1,
                  Length(sPath)-1);
  end;
comments

HOW TO CLEAR MULTIPLE EDIT CONTROLS WITHOUT HAVING TO REFER TO THEM ONE BY ONE


So your new form has 40 edit controls, and now you're looking for a quick and easy way to clear all of them without having to refer to them one by one. How about using a function like this: 
procedure TForm1.Button1Click(Sender: TObject);
var
  i : integer;
begin
  for i := 0 to ComponentCount-1 do
    begin
      if( Components[ i ] is TEdit )then
      begin
        (Components[ i ] as TEdit).Text := '';
      end;
  end;
end;



comments

TWO WAYS TO CHANGE THE DEFAULT PROJECT OPTIONS


You can change the default project options (which is being used by every new project you create) from Delphi GUI:
  1. Create a new project (File | New Application)
  2. Go to "Project | Options" and change the options as you wish.
  3. Check "Default" checkbox in the tabs which you changed options in.
If you rather change the options "manually," you can do so using a simple text editor:

  1. Edit defproj.dof file located in your Delphi's BIN directory (C:\Program Files\Borland\Delphi 2.0\Bin for example) using Notepad or any other text editor. If you don't see the defproj.dof, create one using your favorite text editor in the Delphi's BIN directory using the following format:

    [Compiler]
    A=1
    B=0
    C=0
    D=1
    E=0
    F=0
    G=1
    H=1
    I=1
    J=1
    K=0
    L=1
    M=0
    N=1
    O=1
    P=1
    Q=0
    R=0
    S=0
    T=0
    U=0
    V=1
    W=0
    X=1
    Y=0
    Z=1
    ShowHints=0
    ShowWarnings=0
    UnitAliases=WinTypes=Windows;
    WinProcs=Windows;DbiTypes=BDE;
    DbiProcs=BDE;DbiErrs=BDE;

    [Linker]
    MapFile=0
    OutputObjs=0
    ConsoleApp=1
    DebugInfo=0
    MinStackSize=16384
    MaxStackSize=1048576
    ImageBase=4194304
    ExeDescription=

    [Directories]
    OutputDir=
    SearchPath=
    Conditionals=

    [Parameters]
    RunParams=

comments

HOW TO CALL INTERNET EXPLORER FROM DELPHI


Now that Internet Explorer is a standard part of Windows NT 4.0 and future versions of Windows [95], you may find it useful to add a hot key to your program which will take the user to your home page. Here's a simple function which will do just that: 
program iexplor;

uses
  Windows, OLEAuto;


procedure OpenInternetExplorer( sURL : string );
const
  csOLEObjName = 'InternetExplorer.Application';
var
  IE        : Variant;
  WinHanlde : HWnd;
comments

IS IT 'C:\PROGRAM FILES' OR 'C:\PROGRA~1'


Here's a way to convert between short 8.3 DOS file names and long file names. 
 
First function will convert long file names to the 8.3 format:
 
// remove following two lines
// if already included
uses
  Windows, SysUtils;

function
  GetShortName( sLongName : string )
  : string;
comments

IS IT 'C:\PROGRAM FILES' OR 'C:\PROGRA~1'


Here's a way to convert between short 8.3 DOS file names and long file names. 
 
First function will convert long file names to the 8.3 format:
 
// remove following two lines
// if already included
uses
  Windows, SysUtils;

function
  GetShortName( sLongName : string )
  : string;
comments

BACKGROUND DELPHI FORM


Of course you could place a "TImage" component on your form and set its "Alignment" to "Client" in order to place a background image on your form. Here's another way: 
  1. Add following code to your form's "Public declarations" section:
     
    bmpBackground : TBitmap;
    Listing #1 : Delphi code. Download code (0.15 KB).
     
  2. Double click on your form and add bitmap initialization code in the "FormCreate" event:
     
comments

DRAG AND DROP FILES ON YOUR PROGRAM


If you want to let your users drag and drop files on your program from the File Manager and Windows Explorer, simply add the code inside //>>> and //<<< to your program as in the following example: 
 
unit dropfile;

interface

uses
  Windows, Messages, SysUtils, Classes,
  Graphics, Controls, Forms, Dialogs;
comments

EXPLORE YOUR DOCUMENTS, PROGRAMS AND URLS


If you like how Windows Explorer and File Manager lets you open documents just by double clicking on them, without openning the associated program first, here's how to achieve similar functionality from your Delphi program: 
 
program shellexe;

uses
  WinTypes, ShellAPI;

procedure OpenObject( sObjectPath : string );
begin
  ShellExecute( 0, Nil, PChar( sObjectPath ),
                 Nil, Nil, SW_NORMAL );
end;
comments

FIND OUT WHERE YOUR PROGRAM IS RUNNING FROM


Sometimes it's necessary to find out the path to the executable file of your program, in order to find out where to get the rest of the files from. In most cases, the current directory would be the directory where your programs are executed from, but this method would not work if your program path is listed in the PATH or if an user executes your program from another directory. 
 
Here's how to get the directory where your programs is located:
 
  MessageDlg(
    'program path =  ' +
    ExtractFilePath( Application.ExeName )
    , mtInformation, [mbOk], 0 );
Listing #1 : Delphi code. Download exepath (0.23 KB).

comments

HOW TO CREATE A CONSOLE MODE PROGRAM


You can write console mode programs, also called command line programs, programs that usually does not use Windows' graphical user interface, using Delphi. 
 
  1. Create a new application using "File | New Application"
     
  2. Go to the "Project Manager" ("View | Project Manager")
     
  3. Remove the default form from the project (highlight the unit and hit DELETE -- do not save changes)
     
  4. Go to "Project Source" ("View | Project Source")
     
  5. Edit your project source file:
comments

CHANGE WINDOWS WALLPAPER FROM YOUR PROGRAM


Many programs including major Internet browsers lets you change the Windows wallpaper. Here's how you can add similar functionality to your program: 
 
program wallpapr;

uses
  Registry, WinProcs;

procedure SetWallpaper(
            sWallpaperBMPPath : String;
            bTile : boolean );
comments

HOW TO ACCESS PORTS


In the old days of DOS and 16bit Windows, writing to ports (serial, printer, game, video and other ports) in your computer was easy; all you had to do was use the "port[]" command. 
 
Delphi no longer supports the "port[]" command, so you may have to use assembly functions as follows:
 
function ReadPortB
         ( wPort : Word ) : Byte;
begin
  asm
    mov dx, wPort
    in al, dx
    mov result, al
  end;
end;
comments

HOW TO LOOK FOR AND HANDLE COMMAND LINE PARAMETERS


Most command line programs and some Windows programs has the ability to look for and handle parameters passed to it such as "/? /HELP /Q". If you want to add similar functionality to your Delphi programs, you can start with a function like this: 
 
program myprog;

uses
  SysUtils;

function CmdLineParamFound(
  sParamName : String ) : Boolean;

const
  { assume that command line parameters
    start with the "/" character }
  c_token = '/';
comments

HOW TO ADD COMPONENTS TO FORMS AT RUN TIME


It's easy and fun to create setup components at design time, but if you must, it's not difficult to create them at run time as well. 
For example, let's say you want to create a "TLabel" object called "Label1" with the caption "hello, world!" at run time and place it on your form at (50, 60) x and y coordinates:  comments

HOW TO ADD COMPONENTS TO FORMS AT RUN TIME


It's easy and fun to create setup components at design time, but if you must, it's not difficult to create them at run time as well. 
For example, let's say you want to create a "TLabel" object called "Label1" with the caption "hello, world!" at run time and place it on your form at (50, 60) x and y coordinates:  comments

CONVERT YOUR TCOLORS TO HEX STRINGS


In Delphi, color is often represented using the TColor object. In HTML documents, color is usually represented using a 6 character hex string. Following function will convert TColor type color values to "Internet-style" color codes: 
 
comments

ADD ANIMATED CURSORS TO YOUR PROGRAM


Animated cursors have become so popular since the good old days of Windows 3.0, now they are a built-in part of the Windows 95 and Windows NT operating systems. Here's how you can use them in your Delphi program: 
const
  cnCursorID1 = 1;
begin
  Screen.Cursors[ cnCursorID1 ] :=
    LoadCursorFromFile(
      'c:\winnt\cursors\piano.ani' );
  Cursor := cnCursorID1;
end;
"c:\winnt\cursors\piano.ani" is of course the name of the animated cursor file andcnCursorID1 (defined as 1) is the index of your newly defined cursor. If you wanted to use more than one animated cursor, simply use a different index number -- cnCursorID2 (or 2) for example

comments

TO ADD OR NOT TO ADD


Here's a function that will check if a given string exist in a string list. You can use it when you want to add only the unique strings to any object with a string list property such as list boxes, memos, etc. 
function StrIsInList(
  sl             : TStrings;
  s              : string;
  bCaseSensitive : boolean )
    : boolean;
var
  n : integer;
begin
  Result := False;
  if( not bCaseSensitive )then
    s := LowerCase( s );  
  for n := 0 to ( sl.Count - 1 ) do
  begin
    if( ( bCaseSensitive and
        ( s = LowerCase(
                sl.Strings[ n ] ) ) )
         or ( s = sl.Strings[ n ] )
      )then
    begin
      Result := True;
      Exit;
    end;
  end;
end;

//
// example on how to use StrIsInList()
//
procedure
  TForm1.Button1Click(Sender: TObject);
begin
  if( not StrIsInList( ListBox1.Items,
                    Edit1.Text, False ) ) then
    ListBox1.Items.Add( Edit1.Text );
end;


comments

FUNCTION TO LIST ALL THE NETWORK DRIVE MAPPINGS

It is very easy to get a list of all the network drive mappings using the following function. Please note that you must create and free the string list that you pass to it. The return value indicates the number of network mappings GetNetworkDriveMappings() was able to find. 
comments

CREATE YOUR OWN HINTS


If you don't quite like the way how Delphi's default hints look like, you can use THintWindowcomponent to create your own customized hint window. Here's an example: 
var
  h : THintWindow;
  r : TRect;
begin
  with r do
  begin
    //
    // set the position and size
    // of the hint window
    //
    left   :=  10;
    top    :=  50;
    right  := 200;
    bottom := 100;
  end;
  h := THintWindow.Create( Self );
  with h do
  begin
    //
    // set the background color
    //
    Color := clRed;

    ActivateHint( r, 'hi there!' );

    //
    // perform your tasks here
    // before closing the hint window
    //
    MessageBox( 0,
      'Press any key to close the '
      + 'hint window',
      'THintWindow',
      MB_OK );
      
    ReleaseHandle;
    Free;
  end;
end;

comments

HOW TO PRINT IN A HURRY


If you want to print text in a hurry without fancy formatting or setting up, try something like: 
var
  f : TextFile;
begin
  AssignFile( f, 'LPT1' );
  Rewrite( f );

  //
  // do your printing here...
  //
  WriteLn( f, 'hello, world!');

  CloseFile( f );
end;

comments

DELETE FILES WITH THE ABILITY TO UNDO OR RECYCLE


Windows will not let the user or your program undo file delete operations that your perform using low-level functions such as DeleteFile() from your program. Following function, however, will delete a file with the ability to undo (recycle) by sending the file to the "Recycle Bin." 
comments

ADD DOCUMENTS TO "START | DOCUMENTS" MENU


By default, Windows will keep track of the documents that you work with and most of the time add them to your "Start | Documents" menu. If you want to add documents to this list from your program (without any user interaction), here's a simple function that can do just that: 
uses ShellAPI, ShlOBJ;

procedure AddToStartDocumentsMenu( 
  sFilePath : string );
begin
  SHAddToRecentDocs( 
    SHARD_PATH, 
    PChar( sFilePath ) );
end;
Now, you can just call AddToStartDocumentsMenu() with the document you want to add. For example:
AddToStartDocumentsMenu( 'c:\windows\MyWork.txt' );

comments

EASY WAY TO AVOID ADDING DUPLICATE ITEMS TO STRING LISTS


String lists (TStringList) are great -- easy to manage, used by many components such as memos, list boxes, combo boxes, etc., and full of features. Here's how to avoid adding duplicate items to string lists: 
var
  sl : TStringList;
begin
  sl := TStringList.Create;
  with sl do
  begin
    Sorted     := True;
    Duplicates := dupIgnore;

    //
    // add your items here
    // all the duplicate items
    // will be ignored
    //
comments

SHOW YOUR ID BEFORE CHANGING THE SYSTEM TIME


Changing the system time using the Win32 API isn't as easy as it was in the Win16 world. This is because in Windows NT environment you have to get certain security permissions before changing the system time. Here's how to put the Windows security guard to sleep and change the time: 
comments

HOW TO MAXIMIZE WITHOUT MAXIMIZING


When you maximize a Windows program, it will usually resize to fill up the full screen (minus the space occupied by primary controls such as the task bar). What if you don't want your application to change it's size to the size of the screen, yet you don't want to disable the maximize function? All you have to do is catch and handle the WM_GetMinMaxInfo message.
Assuming that the name of your main form's class is TForm1 and that you want your application to "maximize" to half the size of the screen:
comments

EASY WAY TO FIND OUT WHICH PROPERTIES SHOULD BE SET WHEN CREATING COMPONENTS AT RUN TIME


One of the greatest strengths of Delphi is the ability to visually design the user interface of an application. This sometimes means that you would be creating most parts of your programs at design time rather than at run time as you go into different parts of your programs. Generally speaking, you can reduce the amount of memory required to run your program by creating memory hungry components at run time -- only when your application requires the functionality of those components. Here's a simple example on how to create components dynamically at run time (how to create a "TLabel" component at run time at 10,10 with the caption "hello, world"): 
comments

LOG OFF, SHUT DOWN, RESTART, OR REBOOT


Some programs require Windows to be restarted once it is installed on the system for the first time. If your program has a similar need, you could use the following function -- WinExit() -- to shut down Windows, restart Windows, or log off the current user from Windows. 
comments

INVISIBLE TITLES


Looking for a quick way to hide your program's title bar? 
 
procedure TForm1.FormCreate(Sender: TObject);
begin
  SetWindowLong( Handle,
    GWL_STYLE,
    GetWindowLong( Handle, GWL_STYLE )
    and not WS_CAPTION );

  ClientHeight := Height;
end;
Listing #1 : Delphi code. Download hidetitl (0.28 KB).

comments

INVISIBLE TITLES


Looking for a quick way to hide your program's title bar? 
 
procedure TForm1.FormCreate(Sender: TObject);
begin
  SetWindowLong( Handle,
    GWL_STYLE,
    GetWindowLong( Handle, GWL_STYLE )
    and not WS_CAPTION );

  ClientHeight := Height;
end;
Listing #1 : Delphi code. Download hidetitl (0.28 KB).

comments

DISABLE SCREENSAVER


If your program needs all the attention of the computer, you might want to temporarily turn off screen savers -- at lease while your program is running. Rather than actually disabling and enabling the Windows screen saver, you can simply tell Windows that you've already handled the call for the default screen saver -- SC_SCREENSAVE.
Insert the following code into the "Public declarations" section of your main form: 
comments

HOW TO SAVE CLIPBOARD DATA TO A FILE


Looking for a way to save the data in the clipboard to a file in a hurry? All you have to do is call the following SaveClipboardTextDataToFile() function with the file name: 
SaveClipboardTextDataToFile( 'c:\temp.txt' );
Please note that the following code is written to handle only text data in the clipboard. You can easily change this by modifying the clipboard data format specified -- CF_TEXT -- and changing the file handling methods. comments

REGISTER YOURSELF IN THE REGISTRY


If you're still using good old INI files in your 32bit Windows programs, well, it's time to switch! The new Windows Registry is faster and space conscious than old INI files.
Following two functions and step by step instructions will take some of the mystery out of using the registry for simple purposes:
comments

HOW TO COMMENT OUT LARGE AMOUNT OF SOURCE CODE


You can use { } or (* *) or // [Delphi 2.x+] to comment out code in Delphi. But, if you have a large amount of code that you want to comment out, none of the above operators may help, depending on whether you have already used those operators in your code. Here's a definitive way to comment out code:
{$IFDEF False}
// your commented code goes here
{$ENDIF}

comments

CAN YOUR VIDEO HANDLE 16, 256, 32768, 16777216, OR MORE COLORS?


You can use WIN API function GetDeviceCaps() to calculate the number of colors supported by the current video mode. To make it even easier to use, here's a function that will simply return the number of maximum simultaneous colors current video device can handle:
comments

BETTER WAY TO DISPLAY [ERROR] MESSAGES


IF YOU DISPLAY MORE THAN A FEW [ERROR] MESSAGES IN YOUR APPLICATION, USING A SIMPLE METHOD SUCH AS THE FOLLOWING MAY NOT BE THE BEST APPROACH:

Application.MessageBox(
  'File not found', 'Error', mb_OK );
Above method of displaying errors will make it harder to modify actual messages since they are distributed all over your application source code. It may be better to have a "centralized" function that can display error messages, or better yet, a centralized function that can display replaceable error messages. Consider the following example: comments

CALLING CREATEPROCESS() THE EASY WAY


If you look up the CreateProcess() function in Win32 help, you'll notice that there are more than three dozen parameters that you can optionally setup before calling it. The good news is that you have to setup only a small number of those parameters to make a simple CreateProcess() call as demonstrated in the following function:
comments

COUNT YOUR WORDS


Looking for a simple function that would return the number of words, anything separated by spaces, in a specified string? Following function will do just that using pointers to strings. If you're new to string handling/parsing you might want to pay close attention to how the following function sets up a pointer to the original string and then travel through it, rather than using s[ 1 ], s[ 2 ], s[ 3 ], etc. 
 
comments

SPLASH WINDOWS FOR ALL YOUR SPECIAL OCCATIONS


Splash windows can be used to dress up many parts of your application. You could use them at the initialization of your application to display copyright and other information, or you could use them to display "please wait messages" while your application is in the middle of long operations. You could also use variations of "splash windows" to display floating tool bars and other properties. Well, you get the picture. Here's how to create a simple splash window dynamically:
comments

GLOBALMEMORYSTATUS() TO THE RESCUE


"GetFreeSystemResources()" Win16 API function is no longer supported in Win32 API, but you can use "GlobalMemoryStatus()" to get even more memory related information: 
var
  ms : TMemoryStatus;
begin
  ms.dwLength := SizeOf( ms );
  GlobalMemoryStatus( ms );
  with ms do
  begin
comments

DETECTING CD-ROM DISC AND OTHER DISK CHANGE USING SERIAL NUMBERS


A simple way to find out if a disc (or disk) was changed is to check its volume serial number. For example, you can use the following function to get the volume serial number of a disc. If your CD-ROM drive name is E:, "GetDiskVolSerialID( 'E' )" will return the serial number we're looking for. You can then store this number in your program and compare it to the serial number returned by the next call to "GetDiskVolSerialID()" function. If they are different, you can safely assume that the disc was changed.
comments

DO YOU HAVE HOT KEYS?


Defining and handling hot keys is very easy:
  • Set your form's "KeyPreview" property to "True."

    KeyPreview := True;
  • Define your form's "KeyDown" event. For example, following code will catch any CTRL+F1[hot] key presses:

    procedure TForm1.FormKeyDown(
      Sender: TObject; var Key: Word;
      Shift: TShiftState );
    begin
      if( (ssCtrl in Shift) and
          (Key = VK_F1) )then
      begin
        // do your thing here...
        MessageBox( Handle,
          'F1 pressed!',
          'Hot Key',
          MB_OK );
      end;
    end;
    
    
comments

SEARCH FOR HELP


Looking for a way to open your application's help file to it's search window? All you have to do is pass the name (and the path) of your help file and the string you want to search for to the following HelpSearch() function:
comments

CONTROL AUTOPLAY (DYNAMICALLY) FROM YOUR PROGRAM


You know how to stop Windows' [CD-ROM] AutoPlay from occurring by holding SHIFT or by changing Windows settings. Here's how to detect whether an AutoPlay is about to occur from your application and then either allowing or stopping it.
We're going to ask Windows to send us a message when the AutoPlay is about to occur. In order to catch this message, first of all we have to override our default Windows message handler -- "WndProc()." You can do this by inserting the following code in your form's (named "Form1" for example) public declarations section:
MsgID_QueryCancelAutoPlay : Word;
    
procedure
  WndProc( var Msg : TMessage );
    override;
Now, type in the following code in the "implementation" section (again, assuming that your form is named "Form1") to actually handle the Windows messages. As you can see, we're only interested in catching "QueryCancelAutoPlay" messages, so we'll let the default (or the inherited) "WndProc()" handle all other messages.
procedure TForm1.
  WndProc( var Msg : TMessage );
begin
  if( MsgID_QueryCancelAutoPlay
      = Msg.Msg )then
  begin
    // set Msg.Result
    //   to 1 to stop AutoPlay or
    //   to 0 to continue with AutoPlay
    Msg.Result := 1;
  end else
    inherited WndProc( Msg );
end;
Finally, we have to ask Windows to actually send a "QueryCancelAutoPlay" message to our message handler by inserting the following code in the "FormCreate()" event (click on your form, go to the "events" tab in the "Object Inspector" and double click on "Create"):
MsgID_QueryCancelAutoPlay
  := RegisterWindowMessage(
       'QueryCancelAutoPlay' );

comments

CONTROL AUTOPLAY (DYNAMICALLY) FROM YOUR PROGRAM


You know how to stop Windows' [CD-ROM] AutoPlay from occurring by holding SHIFT or by changing Windows settings. Here's how to detect whether an AutoPlay is about to occur from your application and then either allowing or stopping it.
We're going to ask Windows to send us a message when the AutoPlay is about to occur. In order to catch this message, first of all we have to override our default Windows message handler -- "WndProc()." You can do this by inserting the following code in your form's (named "Form1" for example) public declarations section:
comments

HOW TO PUT A DELAY


Looking for a way to delay the execution of your program? Well, delay() function is gone, but Sleep() and SleepEx() Windows functions are here to stay:
For example, if you want to delay your program execution for 10 seconds, call Windows API function Sleep() with 10*1000 (convert seconds to milliseconds):
Sleep( 10000 );


comments

FIND OUT IF THE CAPS LOCK IS ON


Here's a function you can use to find out if the CAPS LOCK is on: 
function IsCapsLockOn : boolean;
begin
  Result := 0 <>
    (GetKeyState(VK_CAPITAL) and $01);
end;


comments

CONVERT FONT ATTRIBUTES TO A STRING AND VISE VERSA


Sometimes it's necessary to represent attributes of certain objects as strings. For example, if your program allows the user to change fonts and you want to save these customized font attributes in the registry, you might want to save these attributes as strings.
Following two functions will let you convert a font object's attributes into a string and then convert formatted string back into font attributes: 
const
  csfsBold      = '|Bold';
  csfsItalic    = '|Italic';
  csfsUnderline = '|Underline';
  csfsStrikeout = '|Strikeout';

//
comments

MOVING TO THE NEXT TAB STOP


You can make your application focus the next control (in the tab order) on your form by using the SelectNext() method.
To move to the next control:
SelectNext( 
  ActiveControl as TWinControl, 
  True, 
  True );
To move to the previous control:
SelectNext( 
  ActiveControl as TWinControl, 
  False, 
  True );


comments

SETTING WINDOWS WALLPAPER REVISITED (WITH NEW TRICKS!)


We demonstrated how to set Windows' wallpaper from your application using our previously featured SetWallpaper() function. Since then we've improved it to support setting the exact position of the wallpaper and the ability to resize the wallpaper to fit the screen.
uses
  Registry, WinProcs, SysUtils;

const
  // WallPaperStyles
  WPS_Tile      = 0;
  WPS_Center    = 1;
  WPS_SizeToFit = 2;
  WPS_XY        = 3;

//
// sWallpaperBMPPath
//   - path to a BMP file
//
// nStyle
//   - any of the above WallPaperStyles
//
// nX, nY
//   - if the nStyle is set to WPS_XY,
//     nX and nY can be used to set the
//     exact position of the wall paper
//
procedure SetWallpaperExt(
  sWallpaperBMPPath : string;
  nStyle,
  nX, nY : integer );
var
  reg    : TRegIniFile;
  s1     : string;
  X, Y   : integer;
begin
  //
  // change registry
  //
  // HKEY_CURRENT_USER\
  //   Control Panel\Desktop
  //     TileWallpaper (REG_SZ)
  //     Wallpaper (REG_SZ)
  //     WallpaperStyle (REG_SZ)
  //     WallpaperOriginX (REG_SZ)
  //     WallpaperOriginY (REG_SZ)
  //
  reg := TRegIniFile.Create(
           'Control Panel\Desktop' );

  with reg do
  begin
    s1 := '0';
    X  := 0;
    Y  := 0;

    case nStyle of
      WPS_Tile  : s1 := '1';
      WPS_Center: nStyle := WPS_Tile;
      WPS_XY    :
      begin
        nStyle := WPS_Tile;
        X := nX;
        Y := nY;
      end;
    end;

    WriteString( '',
      'Wallpaper',
      sWallpaperBMPPath );

    WriteString( '',
      'TileWallpaper',
      s1 );

    WriteString( '',
      'WallpaperStyle',
      IntToStr( nStyle ) );

    WriteString( '',
      'WallpaperOriginX',
      IntToStr( X ) );

    WriteString( '',
      'WallpaperOriginY',
      IntToStr( Y ) );
  end;
  reg.Free;

  //
  // let everyone know that we
  // changed a system parameter
  //
  SystemParametersInfo(
    SPI_SETDESKWALLPAPER,
    0,
    Nil,
    SPIF_SENDWININICHANGE );
end;
Here are two examples on how to call the above SetWallpaperExt() function.
// set wallpaper to winnt.bmp and
  // stretch it to fit the screen
  SetWallpaperExt(
    'c:\winnt\winnt.bmp',
    WPS_SizeToFit, 0, 0 );

  // set the wallpaper origin
  // to (10, 200)
  SetWallpaperExt(
    'c:\winnt\winnt.bmp',
    WPS_XY, 10, 200 );

comments