• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1365
  • Last Modified:

Convert From C++ To Delphi

hi
please help me by Convert this Code To delphi

////////////////////////////////////////////////////////////////
// MSDN Magazine -- September 2002
// If this code works, it was written by Paul DiLascia.
// If not, I don't know who wrote it.
// Compiles with Visual Studio 6.0 and Visual Studio .NET on Windows XP.
//
// This file implements the low-level keyboard hook that traps the task keys.
//
#define _WIN32_WINNT 0x0500 // for KBDLLHOOKSTRUCT
#include <afxwin.h>         // MFC core and standard components

#define DLLEXPORT __declspec(dllexport)

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//////////////////
// App (DLL) object
//
class CTaskKeyHookDll : public CWinApp {
public:
      CTaskKeyHookDll()  { }
      ~CTaskKeyHookDll() { }
} MyDll;

////////////////
// The section is SHARED among all instances of this DLL.
// A low-level keyboard hook is always a system-wide hook.
//
#pragma data_seg (".mydata")
HHOOK g_hHookKbdLL = NULL; // hook handle
BOOL  g_bBeep = FALSE;            // beep on illegal key
#pragma data_seg ()
#pragma comment(linker, "/SECTION:.mydata,RWS") // tell linker: make it shared

/////////////////
// Low-level keyboard hook:
// Trap task-switching keys by returning without passing along.
//
LRESULT CALLBACK MyTaskKeyHookLL(int nCode, WPARAM wp, LPARAM lp)
{
      KBDLLHOOKSTRUCT *pkh = (KBDLLHOOKSTRUCT *) lp;

      if (nCode==HC_ACTION) {
            BOOL bCtrlKeyDown =
                  GetAsyncKeyState(VK_CONTROL)>>((sizeof(SHORT) * 8) - 1);

            if ((pkh->vkCode==VK_ESCAPE && bCtrlKeyDown) ||                            // Ctrl+Esc
                   (pkh->vkCode==VK_TAB && pkh->flags & LLKHF_ALTDOWN) ||   // Alt+TAB
                   (pkh->vkCode==VK_ESCAPE && pkh->flags & LLKHF_ALTDOWN)|| // Alt+Esc
                   (pkh->vkCode==VK_LWIN || pkh->vkCode==VK_RWIN)) { // Start Menu
                  if (g_bBeep && (wp==WM_SYSKEYDOWN||wp==WM_KEYDOWN))
                        MessageBeep(0); // only beep on downstroke if requested
                  return 1; // gobble it: go directly to jail, do not pass go
            }
      }
      return CallNextHookEx(g_hHookKbdLL, nCode, wp, lp);
}

//////////////////
// Are task keys disabled--ie, is hook installed?
// Note: This assumes there's no other hook that does the same thing!
//
DLLEXPORT BOOL AreTaskKeysDisabled()
{
      return g_hHookKbdLL != NULL;
}

//////////////////
// Disable task keys: install low-level kbd hook.
// Return whether currently disabled or not.
//
DLLEXPORT BOOL DisableTaskKeys(BOOL bDisable, BOOL bBeep)
{
      if (bDisable) {
            if (!g_hHookKbdLL) {
                  g_hHookKbdLL = SetWindowsHookEx(WH_KEYBOARD_LL,
                        MyTaskKeyHookLL, MyDll.m_hInstance, 0);
            }

      } else if (g_hHookKbdLL != NULL) {
            UnhookWindowsHookEx(g_hHookKbdLL);
            g_hHookKbdLL = NULL;
      }
      g_bBeep = bBeep;

      return AreTaskKeysDisabled();
}

This code is from microsft MSDN to Disable Task Keys ( Ctrl+Esc  &  Alt+Esc   &   Alt+Tab )
0
mahdiparak
Asked:
mahdiparak
  • 2
1 Solution
 
Russell LibbySoftware Engineer, Advisory Commented:

I have successfully converted this to Delphi, and have confirmed that it works. My concern at this point is the fact that of the 11 questions you have asked, 9 of them are still open. Hopefully you will respect your end of the deal as the asker of the question.

Regards,
Russell

--- Library source code ---
////////////////////////////////////////////////////////////////////////////////
//   Library     :  TaskKeyHook
////////////////////////////////////////////////////////////////////////////////
library TaskKeyHook;

////////////////////////////////////////////////////////////////////////////////
//   Include units
////////////////////////////////////////////////////////////////////////////////
uses
  Windows, Messages, SysUtils, Classes, SharedMem;

////////////////////////////////////////////////////////////////////////////////
//   Resource includes
////////////////////////////////////////////////////////////////////////////////
{$R *.RES}

////////////////////////////////////////////////////////////////////////////////
//   Constants
////////////////////////////////////////////////////////////////////////////////
const
  SM_NAME           =  'TaskKeyHook';
  WH_KEYBOARD_LL    =  13;
  LLKHF_EXTENDED    =  $0001;
  LLKHF_INJECTED    =  $0010;
  LLKHF_ALTDOWN     =  $0020;
  LLKHF_UP          =  $0080;

////////////////////////////////////////////////////////////////////////////////
//   Structures
////////////////////////////////////////////////////////////////////////////////
type
  TSharedData       =  packed record
     hookVal:       HHOOK;
     boolVal:       BOOL;
  end;

  KBDLLHOOKSTRUCT   =  packed record
    vkCode:         DWORD;
    scanCode:       DWORD;
    flags:          DWORD;
    time:           DWORD;
    dwExtraInfo:    Pointer;
  end;
  PKBDLLHOOKSTRUCT  =  ^KBDLLHOOKSTRUCT;

////////////////////////////////////////////////////////////////////////////////
//   Global variables
////////////////////////////////////////////////////////////////////////////////
var
  smTaskKeyHook:    TSharedMemory  =  nil;
  g_hHookKbdLL:     HHOOK          =  0;
  g_bBeep:          BOOL           = False;

////////////////////////////////////////////////////////////////////////////////
//   Hook callback
////////////////////////////////////////////////////////////////////////////////
function MyTaskKeyHookLL(nCode: Integer; wp, lp: Integer): Integer; stdcall;
var  pkh:           PKBDLLHOOKSTRUCT;
     bCtrlKeyDown:  BOOL;
begin

  pkh:=PKBDLLHOOKSTRUCT(lp);
  if (nCode = HC_ACTION) then
  begin
     bCtrlKeyDown:=((GetAsyncKeyState(VK_CONTROL) shr ((SizeOf(SHORT) * 8) - 1)) <> 0);
     if (
         ((pkh^.vkCode = VK_ESCAPE) and bCtrlKeyDown) or                           // Ctrl+Esc
         ((pkh^.vkCode = VK_TAB) and ((pkh^.flags and LLKHF_ALTDOWN) <> 0)) or     // Alt+Tab
         ((pkh^.vkCode = VK_ESCAPE) and ((pkh^.flags and LLKHF_ALTDOWN) <> 0)) or  // Alt+Esc
         ((pkh^.vkCode = VK_LWIN) or (pkh^.vkCode = VK_RWIN))
        ) then
     begin
        if (g_bBeep and ((wp = WM_SYSKEYDOWN) or (wp = WM_KEYDOWN))) then MessageBeep(0);
        result:=1; // gobble it: go directly to jail, do not pass go
        exit;
     end;
  end;
  result:=CallNextHookEx(g_hHookKbdLL, nCode, wp, lp);

end;

////////////////////////////////////////////////////////////////////////////////
//   Hook check
////////////////////////////////////////////////////////////////////////////////
function AreTaskKeysDisabled: BOOL; stdcall; export;
begin

  result:=not(g_hHookKbdLL = 0);

end;

////////////////////////////////////////////////////////////////////////////////
//   Hook install / uninstall
////////////////////////////////////////////////////////////////////////////////
function DisableTaskKeys(bDisable: BOOL; bBeep: BOOL): BOOL; stdcall; export;
var  sdState:       TSharedData;
begin

  // Resource protection
  try
     // Chek disable
     case bDisable of
        False :
        begin
           UnhookWindowsHookEx(g_hHookKbdLL);
           g_hHookKbdLL:=0;
        end;
        True  :  if (g_hHookKbdLL = 0) then g_hHookKbdLL:=SetWindowsHookEx(WH_KEYBOARD_LL, MyTaskKeyHookLL, hInstance, 0);
     end;
     g_bBeep:=bBeep;
  finally
     // Update shared memory state
     sdState.hookVal:=g_hHookKbdLL;
     sdState.boolVal:=g_bBeep;
     smTaskKeyHook.Write(sdState, SizeOf(sdState));
  end;

  // Return current state
  result:=AreTaskKeysDisabled;

end;

procedure DllMain(Reason: Integer);
var  sdState:       TSharedData;
begin

  // Handle attach and detach
  case Reason of
     // Cleanup
     DLL_PROCESS_DETACH   :
     begin
        // Free shared memory handler
        smTaskKeyHook.Free;
     end;
     // Startup
     DLL_PROCESS_ATTACH   :
     begin
        // Create shared memory handler
        smTaskKeyHook:=TSharedMemory.Create(SM_NAME, SizeOf(TSharedData));
        // Check status of shared memory
        if (smTaskKeyHook.Status = msCreated) then
           // Clear variables
           smTaskKeyHook.Clear
        else
        begin
           // Read the variables in
           smTaskKeyHook.Read(sdState, SizeOf(sdState));
           // Update variables
           g_hHookKbdLL:=sdState.hookVal;
           g_bBeep:=sdState.boolVal;
        end;
     end;
  end;

end;

////////////////////////////////////////////////////////////////////////////////
//   Exports
////////////////////////////////////////////////////////////////////////////////
exports
  AreTaskKeysDisabled,
  DisableTaskKeys;

begin

  // Entry point into library
  DLLProc:=@DllMain;

  // We must now send the process attach
  DllMain(DLL_PROCESS_ATTACH);

end.


-- SharedMem include unit--
unit SharedMem;
////////////////////////////////////////////////////////////////////////////////
//
//   Unit        :  SharedMem
//   Author      :  rllibby
//   Date        :  10.04.2005
//   Description :  Object wrapper around a shared memory block
//
////////////////////////////////////////////////////////////////////////////////
interface

////////////////////////////////////////////////////////////////////////////////
//   Include units
////////////////////////////////////////////////////////////////////////////////
uses
  Windows, SysUtils;

////////////////////////////////////////////////////////////////////////////////
//   Shared memory data types
////////////////////////////////////////////////////////////////////////////////
type
  PCardinal         =  ^Cardinal;

////////////////////////////////////////////////////////////////////////////////
//   Shared memory types
////////////////////////////////////////////////////////////////////////////////
type
  TMemoryStatus     =  (msCreated, msOpened);

////////////////////////////////////////////////////////////////////////////////
//   Shared memory constants
////////////////////////////////////////////////////////////////////////////////
const
  MS_OPENED:        Array [False..True] of TMemoryStatus = (msCreated, msOpened);
  MS_UNIQUE         =  '_sm_mutex';

////////////////////////////////////////////////////////////////////////////////
//   TSharedMemory
////////////////////////////////////////////////////////////////////////////////
type
  TSharedMemory     =  class(TObject)
  private
     // Private declarations
     FStatus:       TMemoryStatus;
     FHandle:       THandle;
     FLockHandle:   THandle;
     FSize:         Cardinal;
     FTag:          Integer;
     FData:         PChar;
     FName:         String;
  protected
     // Protected declarations
     procedure      AquireLock;
     procedure      ReleaseLock;
  public
     // Public declarations
     constructor    Create(Name: String; Size: Cardinal);
     destructor     Destroy; override;
     procedure      Clear;
     function       Read(var Buffer; Count: Cardinal): Cardinal;
     function       Write(const Buffer; Count: Cardinal): Cardinal;
     property       Handle: THandle read FHandle;
     property       Name: String read FName;
     property       Size: Cardinal read FSize;
     property       Status: TMemoryStatus read FStatus;
     property       Tag: Integer read FTag write FTag;
  end;

implementation

//// Utility Functions /////////////////////////////////////////////////////////
function Min(X1, X2: Cardinal): Cardinal;
begin

  // Check for min value
  if (X1 < X2) then
     // Return first param
     result:=X1
  else
     // Return second param
     result:=X2;

end;

function IsHandle(Handle: THandle): Boolean;
begin

  // Check for valid handle
  result:=(Handle <> 0);

end;

//// TSharedMemory /////////////////////////////////////////////////////////////
procedure TSharedMemory.AquireLock;
begin

  // Check mutex
  if (FLockHandle <> INVALID_HANDLE_VALUE) then
  begin
     // Aquire the handle
     WaitForSingleObject(FLockHandle, INFINITE);
  end;

end;

procedure TSharedMemory.ReleaseLock;
begin

  // Check mutex
  if (FLockHandle <> INVALID_HANDLE_VALUE) then
  begin
     // Release ownership
     ReleaseMutex(FLockHandle);
  end;

end;

procedure TSharedMemory.Clear;
var  dwCount:       Cardinal;
begin

  // Aquire lock
  AquireLock;

  // Resource protection
  try
     // Check memory pointer and clear memory
     if Assigned(FData) then ZeroMemory(FData, FSize);
  finally
     // Release lock
     ReleaseLock;
  end;

end;

function TSharedMemory.Read(var Buffer; Count: Cardinal): Cardinal;
var  dwCount:       Cardinal;
begin

  // Aquire lock
  AquireLock;

  // Resource protection
  try
     // Check memory pointer
     if Assigned(FData) then
     begin
        // Get size to read
        dwCount:=Min(FSize, Count);
        // Copy memory to buffer
        System.Move(FData^, Buffer, dwCount);
        // Result is the number of bytes copied
        result:=dwCount;
     end
     else
        // Pointer is nil, nothing to read
        result:=0;
  finally
     // Release lock
     ReleaseLock;
  end;

end;

function TSharedMemory.Write(const Buffer; Count: Cardinal): Cardinal;
var  dwCount:       Cardinal;
begin

  // Aquire lock
  AquireLock;

  // Resource protection
  try
     // Check memory pointer
     if Assigned(FData) then
     begin
        // Get size to write
        dwCount:=Min(FSize, Count);
        // Copy buffer to shared memory
        System.Move(Buffer, FData^, dwCount);
        // Result is the number of bytes copied
        result:=dwCount;
     end
     else
        // Pointer is nil, can't write
        result:=0;
  finally
     // Release lock
     ReleaseLock;
  end;

end;

constructor TSharedMemory.Create(Name: String; Size: Cardinal);
begin

  // Perform inherited
  inherited Create;

  // Set defaults
  FName:=Name;
  FSize:=Size;
  FTag:=0;
  FLockHandle:=0;
  FData:=nil;

  // Create the file handle
  FHandle:=CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE or SEC_COMMIT, 0, FSize+SizeOf(Cardinal), PChar(FName));

  // Check handle
  if not(IsHandle(FHandle)) then
     // Raise exception, failed to create file mapping handle
     RaiseLastWin32Error
  else
  begin
     // Get the status for the memory block
     FStatus:=MS_OPENED[(GetLastError = ERROR_ALREADY_EXISTS)];
     // Map the view of the file
     FData:=MapViewOfFile(FHandle, FILE_MAP_ALL_ACCESS, 0, 0, FSize);
     // Check the mapping
     if Assigned(FData) then
     begin
        // Resource protection
        try
           // If we created the mapping, then set size bytes to null
           if (FStatus = msCreated) then
           begin
              // Clear starting memory buffer
              ZeroMemory(FData, FSize);
              // Set the data size for the buffer
              PCardinal(FData)^:=FSize;
           end
           else
              // Get the stored data size
              FSize:=PCardinal(FData)^;
        finally
           // Push the pointer past the data size indicator
           Inc(FData, SizeOf(Cardinal));
        end;
        // Create mutex handle for accessing the data
        FLockHandle:=CreateMutex(nil, False, PChar(Name+MS_UNIQUE));
     end;
  end;

end;

destructor TSharedMemory.Destroy;
begin

  // Resource protection
  try
     // Should we be unmapping/closing the view/handle
     if IsHandle(FHandle) then
     begin
        // Resource protection
        try
           // Check data
           if Assigned(FData) then
           begin
              // Need to reset back to actual base address
              Dec(FData, SizeOf(Cardinal));
              // Unmap view of file
              UnmapViewOfFile(FData);
           end;
        finally
           // Close handle
           CloseHandle(FHandle);
        end;
     end;
     // Check mutex handle, close if valid
     if IsHandle(FLockHandle) then CloseHandle(FLockHandle);
  finally
     // Perform inherited
     inherited Destroy;
  end;

end;

end.

-- Example program that uses the dll --
nterface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

function   AreTaskKeysDisabled: BOOL; stdcall; external 'TaskKeyHook';
function   DisableTaskKeys(bDisable: BOOL; bBeep: BOOL): BOOL; stdcall; external 'TaskKeyHook';

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin

  if AreTaskKeysDisabled then
     ShowMessage('Disabled')
  else
     ShowMessage('Enabled');

end;

procedure TForm1.Button2Click(Sender: TObject);
begin

  DisableTaskKeys(False, True);

end;

procedure TForm1.Button3Click(Sender: TObject);
begin

  DisableTaskKeys(True, True);

end;

end.

0
 
mahdiparakAuthor Commented:
very very very very thanks
0
 
Russell LibbySoftware Engineer, Advisory Commented:
You are very welcome,
Russell
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now