1. Computing & Technology

Discuss in my forum

Programmatically Enable and Disable CD Auto-Run / Auto-Play

By , About.com Guide

When a user inserts a CD into a CD drive, Windows AutoRun feature opens up an instance of Windows Explorer to display the content of the CD.

There are many situations where AutoRun may need to be temporarily or persistently disabled. For example, AutoRun might interfere with the operation of your Delphi application (asking for a user to insert a series of CDs) and need to be disabled for the duration.

Note: users can manually suppress AutoRun by holding down the SHIFT key when they insert the CD/DVD. However, it is usually preferable to handle this operation programmatically rather than depending on the user.

When a user inserts a CD, Windows sends a "QueryCancelAutoPlay" to the active window. The message handler should return TRUE to cancel AutoRun and FALSE to enable it.

To catch the "QueryCancelAutoPlay" message you need to plug into the "WndProc" method of your main form.
To disable autorun you need to assign 1 to the Result field of the TMessage structure received by "QueryCancelAutoPlay"...

  1. Drop a TCheckBox (name: "chkNoAutoPlay") on a Delphi form (TAutoPlayForm).
  2. In the OnCreate event handler, "RegisterWindowMessage" to make sure Windows sends the "QueryCancelAutoPlay" message to your form when it is active.
  3. Use the WindowProc method to subclass the window procedure of the form (to be able to respond to the auto-play message).
  4. If the check box is checked, the WindowProcedure will assign 1 to the Result field of the Msg parameter - thus disable the auto-play.
 type
    TAutoPlayForm = class(TForm)
      chkNoAutoPlay: TCheckBox;
      procedure FormCreate(Sender: TObject) ;
    private
      procedure WindowProcedure(var Msg : TMessage) ;
    end;
 
 var
    AutoPlayForm: TAutoPlayForm;
 
    Message_QueryCancelAutoPlay : Cardinal;
 
 implementation
 
 {$R *.dfm}
 
 procedure TAutoPlayForm.WindowProcedure(var Msg: TMessage) ;
 begin
    if (Message_QueryCancelAutoPlay = Msg.Msg) then
    begin
      if chkNoAutoPlay.Checked then
        Msg.Result := 1 //disable auto-play
      else
        Msg.Result := 0; //enable auto-play
    end
    else
      inherited WndProc (Msg) ;
 end;
 
 procedure TAutoPlayForm.FormCreate(Sender: TObject) ;
 begin
    Self.WindowProc := WindowProcedure;
 
    Message_QueryCancelAutoPlay := RegisterWindowMessage('QueryCancelAutoPlay') ;
 end; 

Delphi tips navigator:
» Programmatically Get and Set the MediaPlayer Sound Volume
« How to Re-Initialize an Object to its Default State

©2012 About.com. All rights reserved.

A part of The New York Times Company.