BeginUpdate and EndUpdate in Delphi

If you use a Delphi component like a ListBox, Memo, TreeList, ListView,… and you add or modify a lot of items (lines, nodes,…), the component’s performance becomes very slow. This is due to the fact that after each change, it is redrawn on the screen. Solution:

 

 ListBox1.Items.BeginUpdate;
 for i := 1 to 10000 do
 ListBox1.Items.Add('abcd');
 ListBox1.Items.EndUpdate;
Advertisements

Export Registry Key in Delphi

var
 R: TRegistry;
 ErrorCode: Integer;
begin
 NTSetPrivilege('SeBackupPrivilege', true);
 R:= TRegistry.Create;
 try
 R.RootKey := HKEY_LOCAL_MACHINE;
 if R.OpenKeyReadOnly('\Software\My Key') then
 begin
 ErrorCode := RegSaveKey(R.CurrentKey, 'export.reg'), nil);
 R.CloseKey;
 if ErrorCode <> ERROR_SUCCESS then
 raise Exception.CreateFmt('Error Code: %u', [ErrorCode]);
 end
 else
 raise Exception.Create('Key does not exist');
 finally
 R.Free;
 end;
end;

Delphi HttpResponse Error Solution

Error: No mapping for the Unicode character exists in the target multi-byte code page

var
HttpClient: THttpClient;
HttpResponse: IHttpResponse;
begin
HttpClient := THTTPClient.Create;
try
HttpResponse := HttpClient.Get(AURL);
//Result := HttpResponse.ContentAsString();
Result := HttpResponse.ContentAsString(TEncoding.ANSI);
finally
HttpClient.Free;
end;
end;

Delphi Elevated Application Drag & Drop

Dragging & dropping files (Explorer) to elevated application:

procedure SetDragAndDropOnSystemsWIthUAC(Wnd : HWND; IsEnabled : boolean);
type
  TChangeWindowMessageFilter = function(Msg : Cardinal; Action : Word) : Bool; stdcall;
const
  Msg_Add = 1;
  WM_COPYGLOBALDATA = $49;
var
  DllHandle : THandle;
  ChangeWindowMessageFilter : TChangeWindowMessageFilter;
begin
  DllHandle := LoadLibrary('user32.dll');
  if DllHandle > 0 then
  begin
    ChangeWindowMessageFilter := GetProcAddress(DllHandle, 'ChangeWindowMessageFilter');
    if Assigned(ChangeWindowMessageFilter) then
    begin
      DragAcceptFiles(Wnd, IsEnabled);
      ChangeWindowMessageFilter(WM_DROPFILES, Msg_Add);
      ChangeWindowMessageFilter(WM_COPYGLOBALDATA, Msg_Add);
    end;
  end;
end;