2015-08-08 111 views
0

目前我通過EnumWindows檢查HWND是否爲控制檯並檢查ClassName。檢查句柄(HWND)是否爲控制檯

function EnumWindows(AHandle: HWND; AParam: LPARAM): BOOL; stdcall; 
var 
    classname: array[0.. 255] of Char; 
begin 
    GetClassName(AHandle, classname, 255); 

    if classname = 'ConsoleWindowClass' then 
    begin 
    // do something 
    Result := False; 
    end 
    else 
    Result := True; 
end; 

我想知道是否有更好的方法來完成這樣的事情?

檢查樣式(或/和ExStyle)是否「更好」?

+0

您是否試圖找到與當前進程或另一個關聯的控制檯窗口? –

+0

@ 500-InternalServerError只是一般。對於自己當前的進程可以使用:function GetConsoleWindow:HWND; STDCALL;外部'kernel32.dll'; – MRSNAPS

+0

在我們可以告訴你如何識別它之前,你需要定義* console的含義。 –

回答

0

您可以使用AttachConsoleFreeConsole檢測其他進程是否提供控制檯。還有一件事要介意:有沒有控制檯窗口的進程,這些窗口都可以使用AttachConsole - 這裏的GetConsoleWindow返回0。在this github repository中有一個很好的解釋。

聲明:

function AttachConsole(dwProcessID: Integer): Boolean; stdcall; external 'kernel32.dll'; 
function FreeConsole(): Boolean; stdcall; external 'kernel32.dll'; 
function GetConsoleWindow: HWND; stdcall; external kernel32; 

枚舉進程

procedure TForm2.FindConsoleWindows(AList: TListBox); 
var 
    LProcHandle: THandle; 
    LResult, LNext: Boolean; 
    LProc: TProcessEntry32; 
begin 
    aList.Items.Clear; 

    LProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 
    LResult := LProcHandle <> INVALID_HANDLE_VALUE; 
    if LResult then 
    try 
     LProc.dwSize := SizeOf(LProc); 
     LNext := Process32First(LProcHandle, LProc); 
     while LNext do begin 
     if AttachConsole(LProc.th32ProcessID) then 
      try 
      AList.Items.Add(IntToStr(LProc.th32ProcessID) + ' has a console ' + IntToStr(GetConsoleWindow())) 
      finally 
      FreeConsole(); 
      end; 
     LNext := Process32Next(LProcHandle, LPRoc); 
     end; 
    finally 
     CloseHandle(LProcHandle); 
    end; 

現金