There are three problems in your code. First, if you allocate memory (GetMem
), you need to free it (FreeMem
):
GetMem(p, 1024);
try
// Do sth with the memory
finally
FreeMem(p);
end;
Second, I don't see the relation between 100
and 800
. In fact, you lie. You allocate a buffer of 100 bytes, and then you tell Windows that it is big enough to hold 800 Unicode characters.
Third, the return value of the function is undefined, unless the comparison is true. Hence, you need either to add result := false
to the beginning of the procedure, or replace the two last lines (before end;
) by
result := string(FromClass) = 'SDIMainFrame'
Anyhow, it's better not to use GetMem
at all. I'd do it like this:
var
CN: array[0..256] of char;
begin
GetClassName(MFhandle, CN, 256)
Also, you should check for errors. If GetClassName
returns 0
, an error occurred. Hence, you could do something like
function Active_window_mf(): boolean;
var
CN: array[0..256] of char;
begin
result := false;
if GetClassName(GetForegroundWindow, CN, 257) > 0 then
result := string(CN) = 'SDIMainFrame';
end;
Update: According to David's excellent point about abstraction levels, it would be nice to do it like this:
function ClassNameFromHWND(const Handle: HWND): string;
var
CN: array[0..256] of char;
begin
result := '';
if GetClassName(Handle, CN, 257) > 0 then
result := CN;
end;
function Active_window_mf(): boolean;
begin
result := ClassNameFromHWND(GetForegroundWindow) = 'SDIMainForm';
end;