Domanda

I use this code to check if outlook is the default mail client:

Function IsOutlookIsDefaultEmailPrg:Boolean;
var
  reg: TRegistry;
  key : string;
begin
  Result := False;
  with TRegistry.Create do
  TRY
    RootKey := HKEY_LOCAL_MACHINE;
    if OpenKeyReadOnly('Software\Clients\Mail') then
    begin
      key := Uppercase(ReadString('')); //default value
    end;
    result :=  (Pos('MICROSOFT OUTLOOK',Key) > 0);
  FINALLY
    Free;
  END;
end;

it works in general, but on some pc's it has been reported not to work, I checked and the registry key was there.

Is Pos case sensitive? Any idea why this cannot work at times? Any better suggestion?

È stato utile?

Soluzione

I see you are using the HKLM key to check the default client but this can be user depended, so you should really check the HKCU entry (and fall back to HKLM if HKCU does not have the entry). I also removed the With statement and used the ContainsText (include StrUtils unit) function instead of Pos :

function IsOutlookTheDefaultEmailClient:Boolean;
var
  Reg : TRegistry;    
begin
  Result := False;
  Reg := TRegistry.Create;
  try
    // first check HKCU
    Reg.RootKey := HKEY_CURRENT_USER;
    if Reg.OpenKeyReadOnly('Software\Clients\Mail') then
     begin
      Result := ContainsText(Reg.ReadString(''), 'Microsoft Outlook');
      Reg.CloseKey;
     end
    // fall back to HKLM
   else
    begin
     Reg.RootKey := HKEY_LOCAL_MACHINE;
     // this part is susceptible to registry virtualization and my need elevation!
     if Reg.OpenKeyReadOnly('Software\Clients\Mail') then
      begin
       Result := ContainsText(Reg.ReadString(''), 'Microsoft Outlook');
       Reg.CloseKey;
      end;
    end;  
  finally
    Reg.Free;
  end;
end;

EDIT

The only time this code can fail is when Registry virtualization comes into play. This is typical in UAC scenarios. Please check on a failing computer if this key exists in regedit:

HKCU\Software\Classes\VirtualStore\MACHINE\SOFTWARE\Clients\Mail

if that is the case, your application will read this key and not the real HKLM key. The only solution is request elevation or run your application as administrator.

Altri suggerimenti

This is my understanding of the issues:

  1. The Pos function is case-sensitive. So if the value is Microsoft Outlook then your test will not find it. You should instead use ContainsText. Not only does that do what you want, but it is much more readable than Pos()>0.
  2. The system checks first in HKCU\Software\Clients\Mail. If no default mail client is found there, then it checks in HKLM\Software\Clients\Mail. You should do likewise.
  3. On Windows 7 and later, both HKCU\Software\Clients and HKLM\Software\Clients\Mail are shared. On earlier versions of Windows they are redirected. There is potential for errors there. You should use KEY_WOW64_64KEY to access the 64 bit view of the registry.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top