Çeşitli kod ipuçları

Delphi'de kod yazma ile ilgili sorularınızı bu foruma yazabilirsiniz.
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

OEM karakterleri ANSI ye çevirmek

Mesaj gönderen ikutluay »

Kod: Tümünü seç

procedure ConvertFile(const FileName: string; fromCodepage: Integer);
var
  ms: TMemoryStream;
begin
  if getOEMCP <> fromCodepage then
    raise Exception.Create('ConvertFile: Codepage doesn't match!');
  ms := TMemoryStream.Create;
  try
    ms.LoadFromFile(FileName);
    // make backup
    ms.Position := 0;
    ms.SaveToFile(ChangeFileExt(FileName, '.BAK'));
    // convert text
    OEMToCharBuff(ms.Memory, ms.Memory, ms.Size);
    // save back to original file
    ms.Position := 0;
    ms.SaveToFile(FileName);
  finally
    ms.Free;
  end;
end;
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

OLE kullanmadan Excel dosyası oluşturmak (super işe yarayaca

Mesaj gönderen ikutluay »

Kod: Tümünü seç

const
  CXlsBof: array[0..5] of Word = ($809, 8, 00, $10, 0, 0);
  CXlsEof: array[0..1] of Word = ($0A, 00);
  CXlsLabel: array[0..5] of Word = ($204, 0, 0, 0, 0, 0);
  CXlsNumber: array[0..4] of Word = ($203, 14, 0, 0, 0);
  CXlsRk: array[0..4] of Word = ($27E, 10, 0, 0, 0);

procedure XlsBeginStream(XlsStream: TStream; const BuildNumber: Word);
begin
  CXlsBof[4] := BuildNumber;
  XlsStream.WriteBuffer(CXlsBof, SizeOf(CXlsBof));
end;

procedure XlsEndStream(XlsStream: TStream);
begin
  XlsStream.WriteBuffer(CXlsEof, SizeOf(CXlsEof));
end;

procedure XlsWriteCellRk(XlsStream: TStream; const ACol, ARow: Word;
  const AValue: Integer);
var
  V: Integer;
begin
  CXlsRk[2] := ARow;
  CXlsRk[3] := ACol;
  XlsStream.WriteBuffer(CXlsRk, SizeOf(CXlsRk));
  V := (AValue shl 2) or 2;
  XlsStream.WriteBuffer(V, 4);
end;

procedure XlsWriteCellNumber(XlsStream: TStream; const ACol, ARow: Word;
  const AValue: Double);
begin
  CXlsNumber[2] := ARow;
  CXlsNumber[3] := ACol;
  XlsStream.WriteBuffer(CXlsNumber, SizeOf(CXlsNumber));
  XlsStream.WriteBuffer(AValue, 8);
end;

procedure XlsWriteCellLabel(XlsStream: TStream; const ACol, ARow: Word;
  const AValue: string);
var
  L: Word;
begin
  L := Length(AValue);
  CXlsLabel[1] := 8 + L;
  CXlsLabel[2] := ARow;
  CXlsLabel[3] := ACol;
  CXlsLabel[5] := L;
  XlsStream.WriteBuffer(CXlsLabel, SizeOf(CXlsLabel));
  XlsStream.WriteBuffer(Pointer(AValue)^, L);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  FStream: TFileStream;
  I, J: Integer;
begin
  FStream := TFileStream.Create('c:\e.xls', fmCreate);
  try
    XlsBeginStream(FStream, 0);
    for I := 0 to 99 do
      for J := 0 to 99 do
      begin
        XlsWriteCellNumber(FStream, I, J, 34.34);
        // XlsWriteCellRk(FStream, I, J, 3434);
        // XlsWriteCellLabel(FStream, I, J, Format('Cell: %d,%d', [I, J]));
      end;
    XlsEndStream(FStream);
  finally
    FStream.Free;
  end;
end;
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

DOS ekranından çıktı yakalamak

Mesaj gönderen ikutluay »

Kod: Tümünü seç

{----------------------------CreateDOSProcessRedirected---------------------------
 Description    : executes a (DOS!) app defined in the CommandLine parameter redirected
                  to take input from InputFile and give output to OutputFile
 Result         : True on success
 Parameters     :
                  CommandLine : the command line for the app, including its full path
                  InputFile   : the ascii file where from the app takes input
                  OutputFile  : the ascii file to which the app's output is redirected
                  ErrMsg      : additional error message string. Can be empty
 Error checking : YES
 Target         : Delphi 2, 3, 4
 Author         : Theodoros Bebekis, email bebekis@otenet.gr
 Notes          :
 Example call   : CreateDOSProcessRedirected('C:\MyDOSApp.exe',
                                             'C:\InputPut.txt',
                                             'C:\OutPut.txt',
                                             'Please, record this message')
-----------------------------------------------------------------------------------}

function CreateDOSProcessRedirected(const CommandLine, InputFile, OutputFile,
  ErrMsg: string): Boolean;
const
  ROUTINE_ID = '[function: CreateDOSProcessRedirected ]';
var
  OldCursor: TCursor;
  pCommandLine: array[0..MAX_PATH] of Char;
  pInputFile, pOutPutFile: array[0..MAX_PATH] of Char;
  StartupInfo: TStartupInfo;
  ProcessInfo: TProcessInformation;
  SecAtrrs: TSecurityAttributes;
  hAppProcess, hAppThread, hInputFile, hOutputFile: THandle;
begin
  Result := False;

  { check for InputFile existence }
  if not FileExists(InputFile) then
    raise Exception.CreateFmt(ROUTINE_ID + #10 + #10 +
      'Input file * %s *' + #10 +
      'does not exist' + #10 + #10 +
      ErrMsg, [InputFile]);

  { save the cursor }
  OldCursor     := Screen.Cursor;
  Screen.Cursor := crHourglass;

  { copy the parameter Pascal strings to null terminated strings }
  StrPCopy(pCommandLine, CommandLine);
  StrPCopy(pInputFile, InputFile);
  StrPCopy(pOutPutFile, OutputFile);

  try

    { prepare SecAtrrs structure for the CreateFile calls
      This SecAttrs structure is needed in this case because
      we want the returned handle can be inherited by child process
      This is true when running under WinNT.
      As for Win95 the documentation is quite ambiguous }
    FillChar(SecAtrrs, SizeOf(SecAtrrs), #0);
    SecAtrrs.nLength        := SizeOf(SecAtrrs);
    SecAtrrs.lpSecurityDescriptor := nil;
    SecAtrrs.bInheritHandle := True;

    { create the appropriate handle for the input file }
    hInputFile := CreateFile(pInputFile,
      { pointer to name of the file }
      GENERIC_READ or GENERIC_WRITE,
      { access (read-write) mode }
      FILE_SHARE_READ or FILE_SHARE_WRITE,
      { share mode } @SecAtrrs,                             { pointer to security attributes }
      OPEN_ALWAYS,                           { how to create }
      FILE_ATTRIBUTE_TEMPORARY,              { file attributes }
      0);                                   { handle to file with attributes to copy }


    { is hInputFile a valid handle? }
    if hInputFile = INVALID_HANDLE_VALUE then
      raise Exception.CreateFmt(ROUTINE_ID + #10 + #10 +
        'WinApi function CreateFile returned an invalid handle value' +
        #10 +
        'for the input file * %s *' + #10 + #10 +
        ErrMsg, [InputFile]);

    { create the appropriate handle for the output file }
    hOutputFile := CreateFile(pOutPutFile,
      { pointer to name of the file }
      GENERIC_READ or GENERIC_WRITE,
      { access (read-write) mode }
      FILE_SHARE_READ or FILE_SHARE_WRITE,
      { share mode } @SecAtrrs,                             { pointer to security attributes }
      CREATE_ALWAYS,                         { how to create }
      FILE_ATTRIBUTE_TEMPORARY,              { file attributes }
      0);                                   { handle to file with attributes to copy }

    { is hOutputFile a valid handle? }
    if hOutputFile = INVALID_HANDLE_VALUE then
      raise Exception.CreateFmt(ROUTINE_ID + #10 + #10 +
        'WinApi function CreateFile returned an invalid handle value' +
        #10 +
        'for the output file * %s *' + #10 + #10 +
        ErrMsg, [OutputFile]);

    { prepare StartupInfo structure }
    FillChar(StartupInfo, SizeOf(StartupInfo), #0);
    StartupInfo.cb          := SizeOf(StartupInfo);
    StartupInfo.dwFlags     := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
    StartupInfo.wShowWindow := SW_HIDE;
    StartupInfo.hStdOutput  := hOutputFile;
    StartupInfo.hStdInput   := hInputFile;

    { create the app }
    Result := CreateProcess(nil,                           { pointer to name of executable module }
      pCommandLine,
      { pointer to command line string }
      nil,                           { pointer to process security attributes }
      nil,                           { pointer to thread security attributes }
      True,                          { handle inheritance flag }
      CREATE_NEW_CONSOLE or
      REALTIME_PRIORITY_CLASS,       { creation flags }
      nil,                           { pointer to new environment block }
      nil,                           { pointer to current directory name }
      StartupInfo,                   { pointer to STARTUPINFO }
      ProcessInfo);                  { pointer to PROCESS_INF }

    { wait for the app to finish its job and take the handles to free them later }
    if Result then
    begin
      WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
      hAppProcess := ProcessInfo.hProcess;
      hAppThread  := ProcessInfo.hThread;
    end
    else
      raise Exception.Create(ROUTINE_ID + #10 + #10 +
        'Function failure' + #10 + #10 +
        ErrMsg);

  finally
    { close the handles
      Kernel objects, like the process and the files we created in this case,
      are maintained by a usage count.
      So, for cleaning up purposes we have to close the handles
      to inform the system that we don't need the objects anymore }
    if hOutputFile <> 0 then CloseHandle(hOutputFile);
    if hInputFile <> 0 then CloseHandle(hInputFile);
    if hAppThread <> 0 then CloseHandle(hAppThread);
    if hAppProcess <> 0 then CloseHandle(hAppProcess);
    { restore the old cursor }
    Screen.Cursor := OldCursor;
  end;
end;
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

diskteki boş ve dolu alan miktarı

Mesaj gönderen ikutluay »

Kod: Tümünü seç

{
  * Place a Button1 and DriveComboBox1 on your form.
  * The function "SetCurrentDir" well be true if the disk in drive
  * The procedure "GetDiskFreeSpaceEx" returns the free and total disk size
}

uses
  SysUtils;

implementation

function GetDiskSize(drive: Char; var free_size, total_size: Int64): Boolean;
var
  RootPath: array[0..4] of Char;
  RootPtr: PChar;
  current_dir: string;
begin
  RootPath[0] := Drive;
  RootPath[1] := ':';
  RootPath[2] := '\';
  RootPath[3] := #0;
  RootPtr := RootPath;
  current_dir := GetCurrentDir;
  if SetCurrentDir(drive + ':\') then
  begin
    GetDiskFreeSpaceEx(RootPtr, Free_size, Total_size, nil);
    // this to turn back to original dir
    SetCurrentDir(current_dir);
    Result := True;
  end
  else
  begin
    Result := False;
    Free_size  := -1;
    Total_size := -1;
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  free_size, total_size: Int64;
begin
  if GetDiskSize(DriveComboBox1.Drive, free_size, total_size) then
    ShowMessage('free space =' +
      IntToStr(free_size) + #13 + 'total size=' +
      IntToStr(total_size))
  else
    ShowMessage('No disk in drive!');
end;
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

bir urlyi tanımlı program ile açmak

Mesaj gönderen ikutluay »

Kod: Tümünü seç

To open a file of your choice with the application associated
with this files i.e a website but all other documents as
well you only need to call the url.dll with a rundll32 command.
Notice the Expression FileProtocolHandler is case sensitive:

Um eine Datei, z.B. eine Webseite oder auch jedes andere
beliebige Dokument/Datei mit dem assoziierten Programm aufzurufen,
bedarf es nur einem Aufruf der url.dll Datei mithilfe von Rundll32.
Bei FileProtocolHandler Groß- und Kleinschribung beachten:

WinExec(PChar('rundll32 url.dll,
        FileProtocolHandler http://www.swissdelphicenter.ch'),
        SW_MAXIMIZE);
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

çalışan programlarınlistesini almak yada x exe çalışıyormu

Mesaj gönderen ikutluay »

Kod: Tümünü seç

uses
  Psapi, tlhelp32;

procedure CreateWin9xProcessList(List: TstringList);
var
  hSnapShot: THandle;
  ProcInfo: TProcessEntry32;
begin
  if List = nil then Exit;
  hSnapShot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if (hSnapShot <> THandle(-1)) then
  begin
    ProcInfo.dwSize := SizeOf(ProcInfo);
    if (Process32First(hSnapshot, ProcInfo)) then
    begin
      List.Add(ProcInfo.szExeFile);
      while (Process32Next(hSnapShot, ProcInfo)) do
        List.Add(ProcInfo.szExeFile);
    end;
    CloseHandle(hSnapShot);
  end;
end;

procedure CreateWinNTProcessList(List: TstringList);
var
  PIDArray: array [0..1023] of DWORD;
  cb: DWORD;
  I: Integer;
  ProcCount: Integer;
  hMod: HMODULE;
  hProcess: THandle;
  ModuleName: array [0..300] of Char;
begin
  if List = nil then Exit;
  EnumProcesses(@PIDArray, SizeOf(PIDArray), cb);
  ProcCount := cb div SizeOf(DWORD);
  for I := 0 to ProcCount - 1 do
  begin
    hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or
      PROCESS_VM_READ,
      False,
      PIDArray[I]);
    if (hProcess <> 0) then
    begin
      EnumProcessModules(hProcess, @hMod, SizeOf(hMod), cb);
      GetModuleFilenameEx(hProcess, hMod, ModuleName, SizeOf(ModuleName));
      List.Add(ModuleName);
      CloseHandle(hProcess);
    end;
  end;
end;

procedure GetProcessList(var List: TstringList);
var
  ovi: TOSVersionInfo;
begin
  if List = nil then Exit;
  ovi.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
  GetVersionEx(ovi);
  case ovi.dwPlatformId of
    VER_PLATFORM_WIN32_WINDOWS: CreateWin9xProcessList(List);
    VER_PLATFORM_WIN32_NT: CreateWinNTProcessList(List);
  end
end;

function EXE_Running(FileName: string; bFullpath: Boolean): Boolean;
var
  i: Integer;
  MyProcList: TstringList;
begin
  MyProcList := TStringList.Create;
  try
    GetProcessList(MyProcList);
    Result := False;
    if MyProcList = nil then Exit;
    for i := 0 to MyProcList.Count - 1 do
    begin
      if not bFullpath then
      begin
        if CompareText(ExtractFileName(MyProcList.Strings[i]), FileName) = 0 then
          Result := True
      end
      else if CompareText(MyProcList.strings[i], FileName) = 0 then Result := True;
      if Result then Break;
    end;
  finally
    MyProcList.Free;
  end;
end;


// Example 1: Is a Exe-File running ?
procedure TForm1.Button1Click(Sender: TObject);
begin
  if EXE_Running('Notepad.exe', False) then
    ShowMessage('EXE is running')
  else
    ShowMessage('EXE is not running');
end;


// Example 2: List running Exe-Files
procedure TForm1.Button3Click(Sender: TObject);
var
  i: Integer;
  MyProcList: TstringList;
begin
  MyProcList := TStringList.Create;
  try
    GetProcessList(MyProcList);
    if MyProcList = nil then Exit;
    for i := 0 to MyProcList.Count - 1 do
      ListBox1.Items.Add(MyProcList.Strings[i]);
  finally
    MyProcList.Free;
  end;
end;

Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

programınızın sonuna bir EXE dosyası gömmek (rc ile)

Mesaj gönderen ikutluay »

Kod: Tümünü seç

1.
Start notepad and create a .rc-file that looks like this:
Starte Notepad und erstelle ein .rc-file, das etwa so aussieht:

TESTFILE EXEFILE C:\Windows\Notepad.exe

(Make sure that the Path to your Exe-File is correct!)
(Stelle sicher, dass der Pfad zur Exe-Datei korrekt ist!)

2.
Save it as myres.rc
Speichere es als myres.rc

3.
Compile the file with brcc32.exe
(in your Delphi-bin directory) to get myres.res
Kompiliere die Datei mit brcc32.exe
(Im Delphi-bin Verzeichnis) um die Datei myres.res zu erhalten.

4.
Copy myres.res to your Project directory.
Kopiere myres.res in das entsprechende Projekt-Verzeichnis.

5.
In your unit write the following:
In der unit, schreibe etwa das folgende:


var
  Form1: TForm1;
  NOTEPAD_FILE: string;

implementation

{$R *.DFM}
{$R MYRES.RES}

function GetTempDir: string;
var
  Buffer: array[0..MAX_PATH] of Char;
begin
  GetTempPath(SizeOf(Buffer) - 1, Buffer);
  Result := StrPas(Buffer);
end;

// Extract the Resource
function ExtractRes(ResType, ResName, ResNewName: string): Boolean;
var
  Res: TResourceStream;
begin
  Result := False;
  Res := TResourceStream.Create(Hinstance, Resname, PChar(ResType));
  try
    Res.SavetoFile(ResNewName);
    Result := True;
  finally
    Res.Free;
  end;
end;

// Execute the file
procedure ShellExecute_AndWait(FileName: string);
var
  exInfo: TShellExecuteInfo;
  Ph: DWORD;
begin
  FillChar(exInfo, SizeOf(exInfo), 0);
  with exInfo do
  begin
    cbSize := SizeOf(exInfo);
    fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
    Wnd := GetActiveWindow();
    ExInfo.lpVerb := 'open';
    lpFile := PChar(FileName);
    nShow := SW_SHOWNORMAL;
  end;
  if ShellExecuteEx(@exInfo) then
  begin
    Ph := exInfo.HProcess;
  end
  else
  begin
    ShowMessage(SysErrorMessage(GetLastError));
    Exit;
  end;
  while WaitForSingleObject(ExInfo.hProcess, 50) <> WAIT_OBJECT_0 do
    Application.ProcessMessages;
  CloseHandle(Ph);
end;

// To Test it
procedure TForm1.Button1Click(Sender: TObject);
begin
  if ExtractRes('EXEFILE', 'TESTFILE', NOTEPAD_FILE) then
    if FileExists(NOTEPAD_FILE) then
    begin
      ShellExecute_AndWait(NOTEPAD_FILE);
      ShowMessage('Notepad finished!');
      DeleteFile(NOTEPAD_FILE);
    end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  NOTEPAD_FILE := GetTempDir + 'Notepad_FROM_RES.EXE';
end;
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

çalışan bir exeyi diskten silen kod

Mesaj gönderen ikutluay »

Kod: Tümünü seç

procedure DeleteEXE;

  function GetTmpDir: string;
  var
    pc: PChar;
  begin
    pc := StrAlloc(MAX_PATH + 1);
    GetTempPath(MAX_PATH, pc);
    Result := string(pc);
    StrDispose(pc);
  end;

  function GetTmpFileName(ext: string): string;
  var
    pc: PChar;
  begin
    pc := StrAlloc(MAX_PATH + 1);
    GetTempFileName(PChar(GetTmpDir), 'uis', 0, pc);
    Result := string(pc);
    Result := ChangeFileExt(Result, ext);
    StrDispose(pc);
  end;
  
var
  batchfile: TStringList;
  batchname: string;
begin
  batchname := GetTmpFileName('.bat');
  FileSetAttr(ParamStr(0), 0);
  batchfile := TStringList.Create;
  with batchfile do
  begin
    try
      Add(':Label1');
      Add('del "' + ParamStr(0) + '"');
      Add('if Exist "' + ParamStr(0) + '" goto Label1');
      Add('rmdir "' + ExtractFilePath(ParamStr(0)) + '"');
      Add('del ' + batchname);
      SaveToFile(batchname);
      ChDir(GetTmpDir);
      ShowMessage('Uninstalling program...');
      WinExec(PChar(batchname), SW_HIDE);
    finally
      batchfile.Free;
    end;
    Halt;
  end;
end;
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

string gride zoom yapmak

Mesaj gönderen ikutluay »

Kod: Tümünü seç

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    grid: TStringGrid;
    BitBtn1: TBitBtn;
    BitBtn2: TBitBtn;
    procedure BitBtn1Click(Sender: TObject);
    procedure BitBtn2Click(Sender: TObject);
  private
    { Private-Deklarationen }
    procedure gridZoom(FFact: Real);
  public
    { Public-Deklarationen }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.gridZoom(FFact: Real);
var 
  x: Integer;
begin
  for x := 0 to grid.colcount - 1 do
    grid.colwidths[x] := round(grid.colwidths[x] * FFact);

  for x := 0 to grid.RowCount - 1 do
    grid.rowheights[x] := round(grid.rowheights[x] * FFact);

  grid.Font.Size := round(grid.rowheights[0] * 0.65);
end;

//Grösser:
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
  gridZoom(1.1);
end;

//Kleiner:
procedure TForm1.BitBtn2Click(Sender: TObject);
begin
  gridZoom(0.9);
end;

end.
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

disk sürücüleri kğme halinde almak

Mesaj gönderen ikutluay »

Kod: Tümünü seç

{
  Adds all fixed drives into Combobox1.
  To enumerate another type of drive,
  i.e all CD-ROMs just change the DRIVE_FIXED constant to DRIVE_CDROM.

  Fügt all fixen Laufwerke in Combobox1 ein.
  Um z.B alle CD-Rom Laufwerke zu ermitteln,
  einfach DRIVE_CDROM anstatt die Konstante DRIVE_FIXED nehmen.
}

procedure List_Drives;
const
  DRIVE_UNKNOWN = 0;
  DRIVE_NO_ROOT_DIR = 1;
  DRIVE_REMOVABLE = 2;
  DRIVE_FIXED = 3;
  DRIVE_REMOTE = 4;
  DRIVE_CDROM = 5;
  DRIVE_RAMDISK = 6;
var
  r: LongWord;
  Drives: array[0..128] of char;
  pDrive: PChar;
begin
  r := GetLogicalDriveStrings(SizeOf(Drives), Drives);
  if r = 0 then Exit;
  if r > SizeOf(Drives) then
    raise Exception.Create(SysErrorMessage(ERROR_OUTOFMEMORY));
  pDrive := Drives;
  while pDrive^ <> #0 do
  begin
    if GetDriveType(pDrive) = DRIVE_FIXED then
      Form1.ComboBox1.Items.Add(pDrive);
    Inc(pDrive, 4);
  end;
end;


 
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

Shell menuye seçenek eklemek

Mesaj gönderen ikutluay »

Kod: Tümünü seç

uses
  Registry;
  
procedure AddFileMenue(FilePrefix, Menue, Command: string);
var
  reg: TRegistry;
  typ: string;
begin
  reg := TRegistry.Create;
  with reg do
  begin
    RootKey := HKEY_CLASSES_ROOT;
    OpenKey('.' + FilePrefix, True);
    typ := ReadString('');
    if typ = '' then
    begin
      typ := Fileprefix + 'file';
      WriteString('', typ);
    end;
    CloseKey;
    OpenKey(typ + '\shell\' + Menue + '\command', True);
    WriteString('', command + ' "%1"');
    CloseKey;
    Free;
  end;
end;

procedure DeleteFileMenue(Fileprefix, Menue: string);
var
  reg: TRegistry;
  typ: string;
begin
  reg := TRegistry.Create;
  with reg do
  begin
    RootKey := HKEY_CLASSES_ROOT;
    OpenKey('.' + Fileprefix, True);
    typ := ReadString('');
    CloseKey;
    OpenKey(typ + '\shell', True);
    DeleteKey(Menue);
    CloseKey;
    Free;
  end;
end;


{ Example / Beispiel:}

procedure TForm1.Button1Click(Sender: TObject);
begin
  { Register the Menuepoint: }

  AddFileMenue('rtf', 'Edit with Notepad', 'C:\Windows\system\notepad.exe');

  {
    If you now click with the right mousebutton on a *.rtf-file then
    you can see a Menuepoint: "Edit with Notepad".
    When Click on that point Notepad opens the file.

    Wenn man nun mit der rechten Maustaste im Explorer auf eine *.rtf-Datei Clickt,
    dann erscheint dort der Menuepunkt "Edit with Notepad".
    Beim Clicken darauf, öffnet Notepad diese Datei.
  }
end;


procedure TForm1.Button2Click(Sender: TObject);
begin
  {
   Unregister the Menuepoint / Undo your changes in the Registry:
   Löscht den Menuepunkt wieder aus der Registry:
  }

  DeleteFileMenue('rtf', 'Edit with Notepad');
end;


Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

Balon ipucu göstermek

Mesaj gönderen ikutluay »

Kod: Tümünü seç

uses
   Commctrl;

procedure ShowBalloonTip(Control: TWinControl; Icon: integer; Title: pchar; Text: PWideChar;
BackCL, TextCL: TColor);
const
  TOOLTIPS_CLASS = 'tooltips_class32';
  TTS_ALWAYSTIP = $01;
  TTS_NOPREFIX = $02;
  TTS_BALLOON = $40;
  TTF_SUBCLASS = $0010;
  TTF_TRANSPARENT = $0100;
  TTF_CENTERTIP = $0002;
  TTM_ADDTOOL = $0400 + 50;
  TTM_SETTITLE = (WM_USER + 32);
  ICC_WIN95_CLASSES = $000000FF;
type
  TOOLINFO = packed record
    cbSize: Integer;
    uFlags: Integer;
    hwnd: THandle;
    uId: Integer;
    rect: TRect;
    hinst: THandle;
    lpszText: PWideChar;
    lParam: Integer;
  end;
var
  hWndTip: THandle;
  ti: TOOLINFO;
  hWnd: THandle;
begin
  hWnd    := Control.Handle;
  hWndTip := CreateWindow(TOOLTIPS_CLASS, nil,
    WS_POPUP or TTS_NOPREFIX or TTS_BALLOON or TTS_ALWAYSTIP,
    0, 0, 0, 0, hWnd, 0, HInstance, nil);
  if hWndTip <> 0 then
  begin
    SetWindowPos(hWndTip, HWND_TOPMOST, 0, 0, 0, 0,
      SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE);
    ti.cbSize := SizeOf(ti);
    ti.uFlags := TTF_CENTERTIP or TTF_TRANSPARENT or TTF_SUBCLASS;
    ti.hwnd := hWnd;
    ti.lpszText := Text;
    Windows.GetClientRect(hWnd, ti.rect);
    SendMessage(hWndTip, TTM_SETTIPBKCOLOR, BackCL, 0);
    SendMessage(hWndTip, TTM_SETTIPTEXTCOLOR, TextCL, 0);
    SendMessage(hWndTip, TTM_ADDTOOL, 1, Integer(@ti));
    SendMessage(hWndTip, TTM_SETTITLE, Icon mod 4, Integer(Title));
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowBalloonTip(Button1, 1, 'Title',
  'Balloon tooltip,http://kingron.myetang.com; updated by Calin', clBlue, clNavy);
end;
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

DRAG edilen dosyaları programımızdan alan kodlar

Mesaj gönderen ikutluay »

Kod: Tümünü seç

{
  This way you can drag and drop files to a specific control in a Delphi form.
  Just create a project and add a ListBox component to Form1.}

{ 1. First, a procedure to handle the message but without handling it. }

interface

procedure WMDROPFILES(var Msg: TMessage);

implementation

procedure TForm1.WMDROPFILES(var Msg: TWMDropFiles);
var
  pcFileName: PChar;
  i, iSize, iFileCount: integer;
begin
  pcFileName := ''; // to avoid compiler warning message
  iFileCount := DragQueryFile(Msg.wParam, $FFFFFFFF, pcFileName, 255);
  for i := 0 to iFileCount - 1 do
  begin
    iSize := DragQueryFile(Msg.wParam, i, nil, 0) + 1;
    pcFileName := StrAlloc(iSize);
    DragQueryFile(Msg.wParam, i, pcFileName, iSize);
    if FileExists(pcFileName) then
      AddFile(pcFileName); // method to add each file
    StrDispose(pcFileName);
  end;
  DragFinish(Msg.wParam);
end;


{
  2. Second, a WindowProc method to replace ListBox1 WindowProc default method
  and a variable to store ListBox1 WindowProc default method.
}

interface

procedure LBWindowProc(var Message: TMessage);

implementation

var
  OldLBWindowProc: TWndMethod;

procedure TForm1.LBWindowProc(var Message: TMessage);
begin
  if Message.Msg = WM_DROPFILES then
    WMDROPFILES(Message); // handle WM_DROPFILES message
  OldLBWindowProc(Message);
  // call default ListBox1 WindowProc method to handle all other messages
end;

{3. In Form1 OnCreate event, initialize all.}

procedure TForm1.FormCreate(Sender: TObject);
begin
  OldLBWindowProc := ListBox1.WindowProc; // store defualt WindowProc
  ListBox1.WindowProc := LBWindowProc; // replace default WindowProc
  DragAcceptFiles(ListBox1.Handle, True); // now ListBox1 accept dropped files
end;


{4. In Form1 OnDestroy event, uninitialize all. Not necesary but a good practice.}

procedure TForm1.FormDestroy(Sender: TObject);
begin
  ListBox1.WindowProc := OldLBWindowProc;
  DragAcceptFiles(ListBox1.Handle, False);
end;


{5. To complete source code, the AddFile method.}

interface

procedure AddFile(sFileName: string);

implementation

procedure TForm1.AddFile(sFileName: string);
begin
  ListBox1.Items.Add(sFilename);
end;

{6. Do not forget to add ShellAPI unit to the uses clause. }

Complete code


unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
    procedure WMDROPFILES(var Msg: TMessage);
    procedure LBWindowProc(var Message: TMessage);
    procedure AddFile(sFileName: string);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

uses
  ShellAPI;

var
  OldLBWindowProc: TWndMethod;

procedure TForm1.AddFile(sFileName: string);
begin
  ListBox1.Items.Add(sFilename);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  OldLBWindowProc := ListBox1.WindowProc; // store defualt WindowProc
  ListBox1.WindowProc := LBWindowProc; // replace default WindowProc
  DragAcceptFiles(ListBox1.Handle, True); // now ListBox1 accept dropped files
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  ListBox1.WindowProc := OldLBWindowProc;
  DragAcceptFiles(ListBox1.Handle, False);
end;

procedure TForm1.LBWindowProc(var Message: TMessage);
begin
  if Message.Msg = WM_DROPFILES then
    WMDROPFILES(Message); // handle WM_DROPFILES message
  OldLBWindowProc(Message);
  // call default ListBox1 WindowProc method to handle all other messages
end;

procedure TForm1.WMDROPFILES(var Msg: TMessage);
var
  pcFileName: PChar;
  i, iSize, iFileCount: integer;
begin
  pcFileName := ''; // to avoid compiler warning message
  iFileCount := DragQueryFile(Msg.wParam, $FFFFFFFF, pcFileName, 255);
  for i := 0 to iFileCount - 1 do
  begin
    iSize := DragQueryFile(Msg.wParam, i, nil, 0) + 1;
    pcFileName := StrAlloc(iSize);
    DragQueryFile(Msg.wParam, i, pcFileName, iSize);
    if FileExists(pcFileName) then
      AddFile(pcFileName); // method to add each file
    StrDispose(pcFileName);
  end;
  DragFinish(Msg.wParam);
end;

end.
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

formdaki kapat düğmesini işlevsiz kılmak

Mesaj gönderen ikutluay »

Kod: Tümünü seç

procedure TFMain.FormCreate(Sender: TObject);
var
  hMenuHandle: Integer;
begin
  hMenuHandle := GetSystemMenu(Handle, False);
  if (hMenuHandle <> 0) then
    DeleteMenu(hMenuHandle, SC_CLOSE, MF_BYCOMMAND);
end;
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

iki richedit i senkronize etmek

Mesaj gönderen ikutluay »

Kod: Tümünü seç

//...
  private
    PRichEdWndProc, POldWndProc: Pointer;
    procedure RichEdWndProc(var Msg: TMessage);
//...


procedure TForm1.FormCreate(Sender: TObject);
begin
  PRichEdWndProc := MakeObjectInstance(RichEdWndProc);
  POldWndProc    := Pointer(SetWindowLong(RichEdit1.Handle, GWL_WNDPROC,
    Integer(PRichEdWndProc)));
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if Assigned(PRichEdWndProc) then
  begin
    SetWindowLong(RichEdit1.Handle, GWL_WNDPROC, Integer(POldWndProc));
    FreeObjectInstance(PRichEdWndProc);
  end;
end;


procedure TForm1.RichEdWndProc(var Msg: TMessage);
begin
  Msg.Result := CallWindowProc(POldWndProc, RichEdit1.Handle, Msg.Msg,
    Msg.wParam, Msg.lParam);

  if (Msg.Msg = WM_VSCROLL) and (LOWORD(Msg.wParam) = SB_THUMBTRACK) then
  begin
    Label1.Caption := 'Pos is ' + IntToStr(HIWORD(Msg.wParam));
    RichEdit2.Perform(Msg.Msg, Msg.wParam, Msg.lParam);
    SetScrollPos(RichEdit2.Handle, SB_VERT, HIWORD(Msg.wParam), True);
  end;
end;


 
Kişi odur ki, koyar dünyada bir eser. Eseri olmayanın yerinde yeller eser./Muhammed Hadimi
http://www.ibrahimkutluay.net
http://www.ibrahimkutluay.net/blog
Cevapla