SendMessageTimeout in Delphi XE4 64-bit produces Access violation

delphi

Solution

You need to null terminate the string. Just switch the declaration to use a `PChar`.

You must also stop casting pointers to 32 bit `Integer` which will truncate a 64 bit pointer to a 32 bit pointer, and that can easily lead to pain.

Since you don't use aResult, pass nil. Your uninitialized pointer is obviously a problem.

procedure BroadcastChange;
begin
  SendMessageTimeout(
    HWND_BROADCAST, 
    WM_SETTINGCHANGE,
    0, 
    LPARAM(PChar('Environment')), 
    SMTO_NORMAL, 
    4000, 
    nil
  );
end;

Problem

I want to Broadcast the change of a few environment variables in my program. So a few other utilities can make use of the new values. When I compile the next routine in Delphy XE4 32-bit on a Windows 7 platform, everything seems to work fine. When I switch in Delphy to the 64-bit platform, the debugger produces an Access Violation. Any suggestions? ``` procedure BroadcastChange; var lParam, wParam : Integer; Buf : Array[0..10] of Char; aResult : PDWORD_PTR; begin Buf := 'Environment'; wParam := 0; lParam := Integer(@Buf[0]); SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, wParam, lParam, SMTO_NORMAL, 4000, aResult ); end; ```

Original source