Ç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

JPG GIF PNG dosyalarının boyutunu bulmak

Mesaj gönderen ikutluay »

Kod: Tümünü seç

unit ImgSize;

interface

uses Classes;


procedure GetJPGSize(const sFile: string; var wWidth, wHeight: Word);
procedure GetPNGSize(const sFile: string; var wWidth, wHeight: Word);
procedure GetGIFSize(const sGIFFile: string; var wWidth, wHeight: Word);


implementation

uses SysUtils;

function ReadMWord(f: TFileStream): Word;
type
  TMotorolaWord = record
    case Byte of
      0: (Value: Word);
      1: (Byte1, Byte2: Byte);
  end;
var
  MW: TMotorolaWord;
begin
  { It would probably be better to just read these two bytes in normally }
  { and then do a small ASM routine to swap them.  But we aren't talking }
  { about reading entire files, so I doubt the performance gain would be }
  { worth the trouble. }
  f.read(MW.Byte2, SizeOf(Byte));
  f.read(MW.Byte1, SizeOf(Byte));
  Result := MW.Value;
end;

procedure GetJPGSize(const sFile: string; var wWidth, wHeight: Word);
const
  ValidSig: array[0..1] of Byte = ($FF, $D8);
  Parameterless = [$01, $D0, $D1, $D2, $D3, $D4, $D5, $D6, $D7];
var
  Sig: array[0..1] of byte;
  f: TFileStream;
  x: integer;
  Seg: byte;
  Dummy: array[0..15] of byte;
  Len: word;
  ReadLen: LongInt;
begin
  FillChar(Sig, SizeOf(Sig), #0);
  f := TFileStream.Create(sFile, fmOpenRead);
  try
    ReadLen := f.read(Sig[0], SizeOf(Sig));

    for x := Low(Sig) to High(Sig) do
      if Sig[x] <> ValidSig[x] then ReadLen := 0;

    if ReadLen > 0 then
    begin
      ReadLen := f.read(Seg, 1);
      while (Seg = $FF) and (ReadLen > 0) do
      begin
        ReadLen := f.read(Seg, 1);
        if Seg <> $FF then
        begin
          if (Seg = $C0) or (Seg = $C1) then
          begin
            ReadLen := f.read(Dummy[0], 3); { don't need these bytes }
            wHeight := ReadMWord(f);
            wWidth  := ReadMWord(f);
          end 
          else 
          begin
            if not (Seg in Parameterless) then
            begin
              Len := ReadMWord(f);
              f.Seek(Len - 2, 1);
              f.read(Seg, 1);
            end 
            else
              Seg := $FF; { Fake it to keep looping. }
          end;
        end;
      end;
    end;
  finally
    f.Free;
  end;
end;

procedure GetPNGSize(const sFile: string; var wWidth, wHeight: Word);
type
  TPNGSig = array[0..7] of Byte;
const
  ValidSig: TPNGSig = (137,80,78,71,13,10,26,10);
var
  Sig: TPNGSig;
  f: tFileStream;
  x: integer;
begin
  FillChar(Sig, SizeOf(Sig), #0);
  f := TFileStream.Create(sFile, fmOpenRead);
  try
    f.read(Sig[0], SizeOf(Sig));
    for x := Low(Sig) to High(Sig) do
      if Sig[x] <> ValidSig[x] then Exit;
    f.Seek(18, 0);
    wWidth := ReadMWord(f);
    f.Seek(22, 0);
    wHeight := ReadMWord(f);
  finally
    f.Free;
  end;
end;


procedure GetGIFSize(const sGIFFile: string; var wWidth, wHeight: Word);
type
  TGIFHeader = record
    Sig: array[0..5] of char;
    ScreenWidth, ScreenHeight: Word;
    Flags, Background, Aspect: Byte;
  end;

  TGIFImageBlock = record
    Left, Top, Width, Height: Word;
    Flags: Byte;
  end;
var
  f: file;
  Header: TGifHeader;
  ImageBlock: TGifImageBlock;
  nResult: integer;
  x: integer;
  c: char;
  DimensionsFound: boolean;
begin
  wWidth  := 0;
  wHeight := 0;

  if sGifFile = '' then
    Exit;

  {$I-}
  FileMode := 0;   { read-only }
  AssignFile(f, sGifFile);
  reset(f, 1);
  if IOResult <> 0 then
    { Could not open file }
    Exit;

  { Read header and ensure valid file. }
  BlockRead(f, Header, SizeOf(TGifHeader), nResult);
  if (nResult <> SizeOf(TGifHeader)) or (IOResult <> 0) or
    (StrLComp('GIF', Header.Sig, 3) <> 0) then
  begin
    { Image file invalid }
    Close(f);
    Exit;
  end;

  { Skip color map, if there is one }
  if (Header.Flags and $80) > 0 then
  begin
    x := 3 * (1 shl ((Header.Flags and 7) + 1));
    Seek(f, x);
    if IOResult <> 0 then
    begin
      { Color map thrashed }
      Close(f);
      Exit;
    end;
  end;

  DimensionsFound := False;
  FillChar(ImageBlock, SizeOf(TGIFImageBlock), #0);
  { Step through blocks. }
  BlockRead(f, c, 1, nResult);
  while (not EOF(f)) and (not DimensionsFound) do
  begin
    case c of
      ',': { Found image }
        begin
          BlockRead(f, ImageBlock, SizeOf(TGIFImageBlock), nResult);
          if nResult <> SizeOf(TGIFImageBlock) then 
          begin
            { Invalid image block encountered }
            Close(f);
            Exit;
          end;
          wWidth := ImageBlock.Width;
          wHeight := ImageBlock.Height;
          DimensionsFound := True;
        end;
      'ÿ': { Skip }
        begin
          { NOP }
        end;
      { nothing else.  just ignore }
    end;
    BlockRead(f, c, 1, nResult);
  end;
  Close(f);
  {$I+}
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

bir metin dosyasının belirtilen bir satırını okumak

Mesaj gönderen ikutluay »

Kod: Tümünü seç

{
 Abstract:
  Im trying to write a function that, given a FileName and a line number
  returns the entire line in a string.
}

{
 The following technique is useful for high-speed processing.
 The sample program file, save it with a .pas or .dpr filename and compile it.
}


{$APPTYPE CONSOLE}
uses SysUtils, Classes;

function GrabLine(const AFileName: string; ALine: Integer): string;
var
  fs: TFileStream;
  buf: packed array[0..4095] of Char;
  bufRead: Integer;
  bufPos: PChar;
  lineStart: PChar;
  tmp: string;
begin
  fs := TFileStream.Create(AFileName, fmOpenRead);
  try
    Dec(ALine);
    bufRead := 0;
    bufPos := nil;

    { read the first line specially }
    if ALine = 0 then
    begin
      bufRead := fs.Read(buf, SizeOf(buf));
      if bufRead = 0 then
        raise Exception.Create('Line not found');
      bufPos := buf;
    end else
      while ALine > 0 do
      begin
        { read in a buffer }
        bufRead := fs.Read(buf, SizeOf(buf));
        if bufRead = 0 then
          raise Exception.Create('Line not found');
        bufPos := buf;
        while (bufRead > 0) and (ALine > 0) do
        begin
          if bufPos^ = #10 then
            Dec(ALine);
          Inc(bufPos);
          Dec(bufRead);
        end;
      end;
    { Found the beginning of the line at bufPos... scan for end.
      2 cases:
        1) we'll find it before the end of this buffer
        2) it'll go beyond this buffer and into n more buffers }
    lineStart := bufPos;
    while (bufRead > 0) and (bufPos^ <> #10) do
    begin
      Inc(bufPos);
      Dec(bufRead);
    end;
    { if bufRead is positive, we'll have found the end and we can leave. }
    SetString(Result, lineStart, bufPos - lineStart);
    { determine if there are more buffers to process }
    while bufRead = 0 do
    begin
      bufRead := fs.Read(buf, SizeOf(buf));
      lineStart := buf;
      bufPos := buf;
      while (bufRead > 0) and (bufPos^ <> #10) do
      begin
        Inc(bufPos);
        Dec(bufRead);
      end;
      SetString(tmp, lineStart, bufPos - lineStart);
      Result := Result + tmp;
    end;
  finally
    fs.Free;
  end;
end;

function GrabLine2(const s: string; ALine: Integer): string;
var
  sl: TStringList;
begin
  sl := TStringList.Create;
  try
    sl.LoadFromFile(s);
    Result := sl[ALine - 1]; // index off by one
  finally
    sl.Free;
  end;
end;

begin
  Writeln(GrabLine(ParamStr(1), StrToInt(ParamStr(2))));
  Writeln(GrabLine2(ParamStr(1), StrToInt(ParamStr(2))));
end.

{

Call it like 'getline testfile.txt 20000', depending on what you call the
.pas (or .dpr) file. For large (i.e. tens of megabytes) files, the (rather
complex) scanning function easily beats the memory expensive StringList
version.

-- Barry
}
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
Kullanıcı avatarı
conari
Üye
Mesajlar: 2102
Kayıt: 27 Nis 2006 03:10
Konum: İstanbul & Gebze Karışık

Mesaj gönderen conari »

Emeğin için teşekkürler,
Bir kaç tane hemen işime yaracak kod çıktı yarın deneyeceğim.
Lakin sitede Makale ve ipuçları diye ayrı bir kısım var orda yapsaydın daha iyi olurdu ama sanırım oraya da taşınacaktır.
Bir kelimenin anlamını öğretsen bile yeter..
ResimResim
Kullanıcı avatarı
haydarxxx
Üye
Mesajlar: 668
Kayıt: 09 May 2005 11:31
Konum: izmir

Mesaj gönderen haydarxxx »

Emeğin için teşekkür ederim.

Kodların ne işe yaradığıyla ilgili kısa açıklamalarda olsaydı daha güzel olurdu. :oops:
ikutluay
Üye
Mesajlar: 2341
Kayıt: 03 Tem 2007 10:13

Mesaj gönderen ikutluay »

haydarxxx yazdı:Emeğin için teşekkür ederim.

Kodların ne işe yaradığıyla ilgili kısa açıklamalarda olsaydı daha güzel olurdu. :oops:

burda bayağı pratik kodlar var.

ilerde kısmetse bloguma yazar oradan burayada atarım. daha atılacak çok kod vardı ama işyerinde anca bu kadar... yarın devam ederim.

yardımcı olduysak ne mutlu
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

metin yada dosya sifreleme için hazır unit kodu

Mesaj gönderen ikutluay »

Kod: Tümünü seç

unit EZCrypt;

{modeled by Ben Hochstrasser(bhoc@surfeu.ch) after some code snippet from borland}

interface

uses Windows, Classes;

type
  TWordTriple = Array[0..2] of Word;

function FileEncrypt(InFile, OutFile: String; Key: TWordTriple): boolean;
function FileDecrypt(InFile, OutFile: String; Key: TWordTriple): boolean;
function TextEncrypt(const s: string; Key: TWordTriple): string;
function TextDecrypt(const s: string; Key: TWordTriple): string;
function MemoryEncrypt(Src: Pointer; SrcSize: Cardinal; Target: Pointer; TargetSize: Cardinal; Key: TWordTriple): boolean;
function MemoryDecrypt(Src: Pointer; SrcSize: Cardinal; Target: Pointer; TargetSize: Cardinal; Key: TWordTriple): boolean;

implementation

function MemoryEncrypt(Src: Pointer; SrcSize: Cardinal; Target: Pointer; TargetSize: Cardinal; Key: TWordTriple): boolean;
var
  pIn, pOut: ^byte;
  i : Cardinal;
begin
  if SrcSize = TargetSize then
  begin
    pIn := Src;
    pOut := Target;
    for i := 1 to SrcSize do
    begin
      pOut^ := pIn^ xor (Key[2] shr 8);
      Key[2] := Byte(pIn^ + Key[2]) * Key[0] + Key[1];
      inc(pIn);
      inc(pOut);
    end;
    Result := True;
  end else
    Result := False;
end;

function MemoryDecrypt(Src: Pointer; SrcSize: Cardinal; Target: Pointer; TargetSize: Cardinal; Key: TWordTriple): boolean;
var
  pIn, pOut: ^byte;
  i : Cardinal;
begin
  if SrcSize = TargetSize then
  begin
    pIn := Src;
    pOut := Target;
    for i := 1 to SrcSize do
    begin
      pOut^ := pIn^ xor (Key[2] shr 8);
      Key[2] := byte(pOut^ + Key[2]) * Key[0] + Key[1];
      inc(pIn);
      inc(pOut);
    end;
    Result := True;
  end else
    Result := False;
end;

function TextCrypt(const s: string; Key: TWordTriple; Encrypt: Boolean): string;
var
  bOK: Boolean;
begin
  SetLength(Result, Length(s));
  if Encrypt then
    bOK := MemoryEncrypt(PChar(s), Length(s), PChar(Result), Length(Result), Key)
  else
    bOK := MemoryDecrypt(PChar(s), Length(s), PChar(Result), Length(Result), Key);
  if not bOK then Result := '';
end;

function FileCrypt(InFile, OutFile: String; Key: TWordTriple; Encrypt: Boolean): boolean;
var
  MIn, MOut: TMemoryStream;
begin
  MIn := TMemoryStream.Create;
  MOut := TMemoryStream.Create;
  Try
    MIn.LoadFromFile(InFile);
    MOut.SetSize(MIn.Size);
    if Encrypt then
      Result := MemoryEncrypt(MIn.Memory, MIn.Size, MOut.Memory, MOut.Size, Key)
    else
      Result := MemoryDecrypt(MIn.Memory, MIn.Size, MOut.Memory, MOut.Size, Key);
    MOut.SaveToFile(OutFile);
  finally
    MOut.Free;
    MIn.Free;
  end;
end;

function TextEncrypt(const s: string; Key: TWordTriple): string;
begin
  Result := TextCrypt(s, Key, True);
end;

function TextDecrypt(const s: string; Key: TWordTriple): string;
begin
  Result := TextCrypt(s, Key, False);
end;

function FileEncrypt(InFile, OutFile: String; Key: TWordTriple): boolean;
begin
  Result := FileCrypt(InFile, OutFile, Key, True);
end;

function FileDecrypt(InFile, OutFile: String; Key: TWordTriple): boolean;
begin
  Result := FileCrypt(InFile, OutFile, Key, False);
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

Dosyaları birbirine ekle ve sıkıştır (RAR solid yapılması gi

Mesaj gönderen ikutluay »

Kod: Tümünü seç

uses
  Zlib;

procedure CompressFiles(Files : TStrings; const Filename : String);
var
  infile, outfile, tmpFile : TFileStream;
  compr : TCompressionStream;
  i,l : Integer;
  s : String;

begin
  if Files.Count > 0 then
  begin
    outFile := TFileStream.Create(Filename,fmCreate);
    try
      { the number of files }
      l := Files.Count;
      outfile.Write(l,SizeOf(l));
      for i := 0 to Files.Count-1 do
      begin
        infile := TFileStream.Create(Files[i],fmOpenRead);
        try
          { the original filename }
          s := ExtractFilename(Files[i]);
          l := Length(s);
          outfile.Write(l,SizeOf(l));
          outfile.Write(s[1],l);
          { the original filesize }
          l := infile.Size;
          outfile.Write(l,SizeOf(l));
          { compress and store the file temporary}
          tmpFile := TFileStream.Create('tmp',fmCreate);
          compr := TCompressionStream.Create(clMax,tmpfile);
          try
            compr.CopyFrom(infile,l);
          finally
            compr.Free;
            tmpFile.Free;
          end;
          { append the compressed file to the destination file }
          tmpFile := TFileStream.Create('tmp',fmOpenRead);
          try
            outfile.CopyFrom(tmpFile,0);
          finally
            tmpFile.Free;
          end;
        finally
          infile.Free;
        end;
      end;
    finally
      outfile.Free;
    end;
    DeleteFile('tmp');
  end;
end;

procedure DecompressFiles(const Filename, DestDirectory : String);
var
  dest,s : String;
  decompr : TDecompressionStream;
  infile, outfile : TFilestream;
  i,l,c : Integer;
begin
  // IncludeTrailingPathDelimiter (D6/D7 only)
  dest := IncludeTrailingPathDelimiter(DestDirectory);

  infile := TFileStream.Create(Filename,fmOpenRead);
  try
    { number of files }
    infile.Read(c,SizeOf(c));
    for i := 1 to c do
    begin
      { read filename }
      infile.Read(l,SizeOf(l));
      SetLength(s,l);
      infile.Read(s[1],l);
      { read filesize }
      infile.Read(l,SizeOf(l));
      { decompress the files and store it }
      s := dest+s; //include the path
      outfile := TFileStream.Create(s,fmCreate);
      decompr := TDecompressionStream.Create(infile);
      try
        outfile.CopyFrom(decompr,l);
      finally
        outfile.Free;
        decompr.Free;
      end;
    end;
  finally
    infile.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

word dosyasının bilgilerini okumak ve değiştirmek

Mesaj gönderen ikutluay »

Kod: Tümünü seç

{ 1. Change MS Word properties via OLE }

uses
  ComObj;

procedure TForm1.Button1Click(Sender: TObject);
const
  wdPropertyTitle = $00000001;
  wdPropertySubject = $00000002;
  wdPropertyAuthor = $00000003;
  wdPropertyKeywords = $00000004;
  wdPropertyComments = $00000005;
  wdPropertyTemplate = $00000006;
  wdPropertyLastAuthor = $00000007;
  wdPropertyRevision = $00000008;
  wdPropertyAppName = $00000009;
  wdPropertyTimeLastPrinted = $0000000A;
  wdPropertyTimeCreated = $0000000B;
  wdPropertyTimeLastSaved = $0000000C;
  wdPropertyVBATotalEdit = $0000000D;
  wdPropertyPages = $0000000E;
  wdPropertyWords = $0000000F;
  wdPropertyCharacters = $00000010;
  wdPropertySecurity = $00000011;
  wdPropertyCategory = $00000012;
  wdPropertyFormat = $00000013;
  wdPropertyManager = $00000014;
  wdPropertyCompany = $00000015;
  wdPropertyBytes = $00000016;
  wdPropertyLines = $00000017;
  wdPropertyParas = $00000018;
  wdPropertySlides = $00000019;
  wdPropertyNotes = $0000001A;
  wdPropertyHiddenSlides = $0000001B;
  wdPropertyMMClips = $0000001C;
  wdPropertyHyperlinkBase = $0000001D;
  wdPropertyCharsWSpaces = $0000001E;
const
  AWordDoc = 'C:\Test.doc';
  wdSaveChanges = $FFFFFFFF;
var
  WordApp: OLEVariant;
  SaveChanges: OleVariant;
begin
  try
    WordApp := CreateOleObject('Word.Application');
  except
    // Error....
    Exit;
  end;
  try
    WordApp.Visible := False;
    WordApp.Documents.Open(AWordDoc);
    WordApp.ActiveDocument.BuiltInDocumentProperties[wdPropertyTitle].Value := 'Your Title...';
    WordApp.ActiveDocument.BuiltInDocumentProperties[wdPropertySubject].Value := 'Your Subject...';
    // ...
    // ...
  finally
    SaveChanges := wdSaveChanges;
    WordApp.Quit(SaveChanges, EmptyParam, EmptyParam);
  end;
end;


{**********************************************}


{
  2. Read MS Word properties via Structured Storage.
  by Serhiy Perevoznyk
}
uses
  ComObj, ActiveX;

const
  FmtID_SummaryInformation: TGUID =
    '{F29F85E0-4FF9-1068-AB91-08002B27B3D9}';

function FileTimeToDateTimeStr(F: TFileTime): string;
var
  LocalFileTime: TFileTime;
  SystemTime: TSystemTime;
  DateTime: TDateTime;
begin
  if Comp(F) = 0 then Result := '-'
  else 
  begin
    FileTimeToLocalFileTime(F, LocalFileTime);
    FileTimeToSystemTime(LocalFileTime, SystemTime);
    with SystemTime do
      DateTime := EncodeDate(wYear, wMonth, wDay) +
        EncodeTime(wHour, wMinute, wSecond, wMilliseconds);
    Result := DateTimeToStr(DateTime);
  end;
end;

function GetDocInfo(const FileName: WideString): string;
var
  I: Integer;
  PropSetStg: IPropertySetStorage;
  PropSpec: array[2..19] of TPropSpec;
  PropStg: IPropertyStorage;
  PropVariant: array[2..19] of TPropVariant;
  Rslt: HResult;
  S: string;
  Stg: IStorage;
begin
  Result := '';
  try
    OleCheck(StgOpenStorage(PWideChar(FileName), nil, STGM_READ or
      STGM_SHARE_DENY_WRITE,
      nil, 0, Stg));
    PropSetStg := Stg as IPropertySetStorage;
    OleCheck(PropSetStg.Open(FmtID_SummaryInformation,
      STGM_READ or STGM_SHARE_EXCLUSIVE, PropStg));
    for I := 2 to 19 do
    begin
      PropSpec[I].ulKind := PRSPEC_PROPID;
      PropSpec[I].PropID := I;
    end;
    Rslt := PropStg.ReadMultiple(18, @PropSpec, @PropVariant);
    OleCheck(Rslt);
    if Rslt <> S_FALSE then for I := 2 to 19 do
      begin
        S := '';
        if PropVariant[I].vt = VT_LPSTR then
          if Assigned(PropVariant[I].pszVal) then
            S := PropVariant[I].pszVal;
        case I of
          2:  S  := Format('Title: %s', [S]);
          3:  S  := Format('Subject: %s', [S]);
          4:  S  := Format('Author: %s', [S]);
          5:  S  := Format('Keywords: %s', [S]);
          6:  S  := Format('Comments: %s', [S]);
          7:  S  := Format('Template: %s', [S]);
          8:  S  := Format('Last saved by: %s', [S]);
          9:  S  := Format('Revision number: %s', [S]);
          10: S := Format('Total editing time: %g sec',
              [Comp(PropVariant[I].filetime) / 1.0E9]);
          11: S := Format('Last printed: %s',
              [FileTimeToDateTimeStr(PropVariant[I].filetime)]);
          12: S := Format('Create time/date: %s',
              [FileTimeToDateTimeStr(PropVariant[I].filetime)]);
          13: S := Format('Last saved time/date: %s',
              [FileTimeToDateTimeStr(PropVariant[I].filetime)]);
          14: S := Format('Number of pages: %d', [PropVariant[I].lVal]);
          15: S := Format('Number of words: %d', [PropVariant[I].lVal]);
          16: S := Format('Number of characters: %d',
              [PropVariant[I].lVal]);
          17:; // thumbnail
          18: S := Format('Name of creating application: %s', [S]);
          19: S := Format('Security: %.8x', [PropVariant[I].lVal]);
        end;
        if S <> '' then Result := Result + S + #13;
      end;
  finally
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if Opendialog1.Execute then
    ShowMessage(GetDocInfo(opendialog1.FileName));
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

Delphiden inf dosyası kurdurmak

Mesaj gönderen ikutluay »

Kod: Tümünü seç

uses
  ShellAPI;

function InstallINF(const PathName: string; hParent: HWND): Boolean;
var
  instance: HINST;
begin
  instance := ShellExecute(hParent,
    PChar('open'),
    PChar('rundll32.exe'),
    PChar('setupapi,InstallHinfSection DefaultInstall 132 ' + PathName),
    nil,
    SW_HIDE);

  Result := instance > 32;
end; { InstallINF }

// Example:

procedure TForm1.Button1Click(Sender: TObject);
begin
  InstallINF('C:\XYZ.inf', 0);
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

klasör seçme dialogu ve inidial dir

Mesaj gönderen ikutluay »

Kod: Tümünü seç

uses
  ShlObj, ActiveX;

function SelectDirectoryEx(hOwn: HWND; var Path: string; Caption, Root: string;
  uFlag: DWORD = $25): Boolean;
const
  BIF_NEWDIALOGSTYLE = $0040;
var
  BrowseInfo: TBrowseInfo;
  Buffer: PChar;
  RootItemIDList, ItemIDList: PItemIDList;
  ShellMalloc: IMalloc;
  IDesktopFolder: IShellFolder;
  Dummy: LongWord;

  function BrowseCallbackProc(hwnd: HWND; uMsg: UINT; lParam: Cardinal;
    lpData: Cardinal): Integer; stdcall;
  var
    PathName: array[0..MAX_PATH] of Char;
  begin
    case uMsg of
      BFFM_INITIALIZED:
        SendMessage(Hwnd, BFFM_SETSELECTION, Ord(True), Integer(lpData));
      BFFM_SELCHANGED:
        begin
          SHGetPathFromIDList(PItemIDList(lParam), @PathName);
          SendMessage(hwnd, BFFM_SETSTATUSTEXT, 0, Longint(PChar(@PathName)));
        end;
    end;
    Result := 0;
  end;
begin
  Result := False;
  FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
  if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then
  begin
    Buffer := ShellMalloc.Alloc(MAX_PATH);
    try
      RootItemIDList := nil;
      if Root <> '' then
      begin
        SHGetDesktopFolder(IDesktopFolder);
        IDesktopFolder.ParseDisplayName(hOwn, nil, POleStr(WideString(Root)),
          Dummy, RootItemIDList, Dummy);
      end;
      with BrowseInfo do
      begin
        hwndOwner := hOwn;
        pidlRoot := RootItemIDList;
        pszDisplayName := Buffer;
        lpszTitle := PChar(Caption);
        ulFlags := uFlag;
        lpfn := @BrowseCallbackProc;
        lParam := Integer(PChar(Path));
      end;
      ItemIDList := ShBrowseForFolder(BrowseInfo);
      Result := ItemIDList <> nil;
      if Result then
      begin
        ShGetPathFromIDList(ItemIDList, Buffer);
        ShellMalloc.Free(ItemIDList);
        Path := StrPas(Buffer);
      end;
    finally
      ShellMalloc.Free(Buffer);
    end;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Path: string;
begin
  Path := 'C:\Windows';
  if SelectDirectoryEx(Handle, Path, 'Select Directory Sample', 'C:\') then
    ShowMessage(Path);
end;


{******************************************************************}

{
  Heres an example on how to locate a folder with a specific filer,
  using SHBrowseForFolder and a BrowseCallBack function
  ( by Jack Kallestrup )
}

uses ShlObj, ShellApi;

function BrowseCallBack ( Hwnd : THandle; uMsg : UINT; lpParam, lpData : LPARAM): integer; stdcall;
var
  Buffer : Array[0..255] of char;
  Buffer2 : Array[0..255] of char;
  TmpStr : String;
begin
  // Initialize buffers
  FillChar(Buffer,SizeOf(Buffer),#0);
  FillChar(Buffer2,SizeOf(Buffer2),#0);

  // Statusline text
  TmpStr := 'Locate folder containing '+StrPas(PChar(lpData));

  // Copy statustext to pchar
  StrPCopy(Buffer2,TmpStr);

  // Send message to BrowseForDlg that
  // the status text has changed
  SendMessage(hwnd,BFFM_SETSTATUSTEXT,0,Integer(@Buffer2));

  // If directory in BrowswForDlg has changed ?
  if uMsg = BFFM_SELCHANGED then begin
    // Get the new folder name
    SHGetPathFromIDList(PItemIDList(lpParam),Buffer);
    // And check for existens of our file.
    {$IFDEF RX_D3}  //RxLib - extentions
    if FileExists(NormalDir(StrPas(Buffer))+StrPas(PChar(lpData)))
       and (StrLen(Buffer) > 0) then
    {$ELSE}
      if Length(StrPas(Buffer)) <> 0 then
       if Buffer[Length(StrPas(Buffer))-1] = '\' then
         Buffer[Length(StrPas(Buffer))-1] := #0;
      if FileExists(StrPas(Buffer)+'\'+StrPas(PChar(lpData))) and
         (StrLen(Buffer) > 0) then
    {$ENDIF}
      // found : Send message to enable OK-button
      SendMessage(hwnd,BFFM_ENABLEOK,1,1)
    else
      // Send message to disable OK-Button
      SendMessage(Hwnd,BFFM_ENABLEOK,0,0);
  end;
  result := 0
end;


function BrowseforFile(Handle : THandle; Title : String; Filename : String) : String;
var
  BrowseInfo : TBrowseInfo;
  RetBuffer,
  FName,
  ResultBuffer : Array[0..255] of char;
  PIDL : PItemIDList;
begin
  StrPCopy(Fname,FileName);

  //Initialize buffers
  FillChar(BrowseInfo,SizeOf(TBrowseInfo),#0);
  Fillchar(RetBuffer,SizeOf(RetBuffer),#0);
  FillChar(ResultBuffer,SizeOf(ResultBuffer),#0);

  BrowseInfo.hwndOwner := Handle;
  BrowseInfo.pszDisplayName := @Retbuffer;
  BrowseInfo.lpszTitle := @Title[1];

  // we want a status-text
  BrowseInfo.ulFlags := BIF_StatusText;

  // Our call-back function cheching for fileexist
  BrowseInfo.lpfn := @BrowseCallBack;
  BrowseInfo.lParam := Integer(@FName);

  // Show BrowseForDlg
  PIDL := SHBrowseForFolder(BrowseInfo);

  // Return fullpath to file
  if SHGetPathFromIDList(PIDL,ResultBuffer) then
    result := StrPas(ResultBuffer)
  else
    Result := '';

  GlobalFreePtr(PIDL);  //Clean up
end;

// Example:

procedure TForm1.Button1Click(Sender: TObject);
const
  FileName = 'File.xyz';
var
  Answer: Integer;
begin
  if MessageBox(0, 'To locate the file yourself, click ok',
     PChar(Format('File %s not found.',[FileName])),MB_OKCANCEL) = 1 then
       BrowseforFile(Handle, 'locate ' + FileName, FileName);
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

NTFS fonksiyonları ile şifreleme

Mesaj gönderen ikutluay »

Kod: Tümünü seç

{
This tip works with Windows 2000 (NTFS 5) and later

These 2 functions are defined in windows.pas, but they're defined wrong. In this
case our own definition.
}

  function EncryptFile(lpFilename: PChar): BOOL; stdcall;
           external advapi32 name 'EncryptFileA';

  function DecryptFile(lpFilename: PChar; dwReserved: DWORD): BOOL; stdcall;
           external advapi32 name 'DecryptFileA';
           
           
{....}


procedure TForm1.Button1Click(Sender: TObject);
begin
  if not EncryptFile('c:\temp') then
    ShowMessage('Can''t encrypt directory.');
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  if not DecryptFile('c:\temp', 0) then
    ShowMessage('Can''t decrypt directory.');
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

başka programa drag drop ile bilgi göndermek

Mesaj gönderen ikutluay »

Kod: Tümünü seç

uses
  ShellAPI;

function MakeDrop(const FileNames: array of string): THandle;
// Creates a hDrop Object
// erzeugt ein hDrop Object
var
  I, Size: Integer;
  Data: PDragInfoA;
  P: PChar;
begin
  // Calculate memory size needed
  // berechne notwendig Speichergröße
  Size := SizeOf(TDragInfoA) + 1;
  for I := 0 to High(FileNames) do
    Inc(Size, Length(FileNames[I]) + 1);
  // allocate the memory
  // alloziere den speicher
  Result := GlobalAlloc(GHND or GMEM_SHARE, Size);
  if Result <> 0 then
  begin
    Data := GlobalLock(Result);
    if Data <> nil then
      try
        // fill up with data
        // fülle daten
        Data.uSize := SizeOf(TDragInfoA);
        P  := PChar(@Data.grfKeyState) + 4;
        Data.lpFileList := P;
        // filenames at the at of the header (separated with #0)
        // am ende des headers nun die filenamen getrennt mit #0
        for I := 0 to High(FileNames) do
        begin
          Size := Length(FileNames[I]);
          Move(Pointer(FileNames[I])^, P^, Size);
          Inc(P, Size + 1);
        end;
      finally
        GlobalUnlock(Result);
      end
    else
    begin
      GlobalFree(Result);
      Result := 0;
    end;
  end;
end;

function MyEnum(Wnd: hWnd; Res: PInteger): Bool; stdcall;
// search for a edit control with classname 'TEditControl'
// suche ein child fenster mit klassennamen 'TEditControl'
var
  N: string;
begin
  SetLength(N, MAX_PATH);
  SetLength(N, GetClassName(Wnd, Pointer(N), Length(N)));
  Result := AnsiCompareText('TEditControl', N) <> 0;
  if not Result then Res^ := Wnd;
end;

// Example: Open msdos.sys in Delphi's Editor window
// Beispiel: msdos.sys im Delphi Editor öffnen
procedure TForm1.Button1Click(Sender: TObject);
var
  Wnd: HWnd;
  Drop: hDrop;
begin
  // search for Delphi's Editor
  // suche Delphis Editor Fenster
  EnumChildWindows(FindWindow('TEditWindow', nil), @MyEnum, Integer(@Wnd));
  if IsWindow(Wnd) then
  begin
    // Delphi's Editor found. Open msdos.sys
    // Delphis editor gefunden, also öffne msdos.sys
    Drop := MakeDrop(['c:\msdos.sys']);
    if Drop <> 0 then PostMessage(Wnd, wm_DropFiles, Drop, 0);
    // Free the memory?
    // Speicher wieder freigeben?
    GlobalFree(Drop);
  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

Bir belgeyi çalıştırmak ve işi bitene kadar beklemek

Mesaj gönderen ikutluay »

Kod: Tümünü seç

{
  This tip allows you to open any document with its
  associated application (not only exe, com) and wait for it to finish.
}


{
  Dieser Tip ermöglicht es, nicht nur normale Programme, sondern auch Dateien,
  die mit Programmen geöffnet werden, auszuführen und darauf zu warten,
  bis sie beendet sind.
}

uses
  Shellapi;

function StartAssociatedExe(FileName: string; var ErrorCode: Cardinal): Boolean;
var
  Prg: string;
  ProcessInfo: TProcessInformation;
  StartupInfo: TStartupInfo;
begin
  SetLength(Prg, MAX_PATH);
  Result := False;
  ErrorCode := FindExecutable(PChar(FileName), nil, PChar(Prg));
  if ErrorCode >= 32 then
  begin
    SetLength(Prg, StrLen(PChar(Prg)));
    FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
    with StartupInfo do
    begin
      cb := SizeOf(TStartupInfo);
      wShowWindow := SW_SHOW;
    end;
    if CreateProcess(PChar(Prg), PChar(Format('%s %s', [Prg, FileName])),
      nil, nil, False, NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then
    begin
      WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
      GetExitCodeProcess(ProcessInfo.hProcess, ErrorCode);
      CloseHandle(ProcessInfo.hProcess);
      CloseHandle(ProcessInfo.hThread);
      Result := True;
    end
    else
      ErrorCode := GetLastError;
  end;
end;

// Example, Beispiel:

procedure TForm1.Button1Click(Sender: TObject);
var
  ErrorCode: Cardinal;
begin
  StartAssociatedExe('c:\test.doc', ErrorCode);
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

gif dosyasının boyutlarını alma

Mesaj gönderen ikutluay »

Kod: Tümünü seç

type
  TImageSize = record
    Width: Integer;
    Height: Integer;
  end;

function ReadGIFSize(Stream: TStream): TImageSize;
type
  TGifHeader = record
    Signature: array [0..5] of Char;
    Width, Height: Word;
  end;
var
  Header: TGifHeader;
begin
  FillChar(Header, SizeOf(TGifHeader), #0);
  Result.Width := -1;
  Result.Height := -1;
  with Stream do
  begin
    Seek(0, soFromBeginning);
    ReadBuffer(Header, SizeOf(TGifHeader));
  end;
  if (AnsiUpperCase(Header.Signature) = 'GIF89A') or
    (AnsiUpperCase(Header.Signature) = 'GIF87A') then
  begin
    Result.Width  := Header.Width;
    Result.Height := Header.Height;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
const
  FileName = 'D:\test.gif';
var
  fs: TFileStream;
  gifsize: TImageSize;
begin
  fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
  try
    gifsize := ReadGIFSize(fs);
    ShowMessage(Format('Breite %d Höhe %d', [gifsize.Width, gifsize.Height]));
  finally
    fs.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ı çalıştırmak ve işi bitene kadar beklemek

Mesaj gönderen ikutluay »

Kod: Tümünü seç

// First create the special unit and put this code into this new unit:

uses
  Windows, Registry, Dialogs, Classes, SysUtils;

var
  aProcessInfo: PROCESS_INFORMATION;
  aProcessSecAttr: SECURITY_ATTRIBUTES;
  aThreadSecAttr: SECURITY_ATTRIBUTES;
  aStartupInfo: STARTUPINFO;

function RunApp(commandLine: String): integer;
var
  n: Boolean;
begin
  with aProcessSecAttr do
  begin
    bInheritHandle := False;
    lpSecurityDescriptor := nil;
    nLength := sizeOf(aProcessSecAttr);
  end;

  with aThreadSecAttr do
  begin
    bInheritHandle := False;
    lpSecurityDescriptor := nil;
    nLength := sizeOf(aThreadSecAttr);
  end;

  with aStartupInfo do
  begin
    cb := sizeOf(aStartupInfo);
    lpReserved := nil;
    lpDesktop := nil;
    lpTitle := nil;
    dwX := 0;
    dwY := 0;
    dwXSize := 300;
    dwYSize := 300;
    dwXCountChars := 80;
    dwYCountChars := 25;
    dwFillAttribute := 0;
    dwFlags := STARTF_USESTDHANDLES;
    wShowWindow := SW_SHOWDEFAULT;
    cbReserved2 := 0;
    lpReserved2 := nil;
    hStdInput := 0;
    hStdError := 0;
    hStdOutput := 0;
  end;

  n := CreateProcess(nil, @commandLine[1], nil, nil,
                     True, CREATE_NO_WINDOW + NORMAL_PRIORITY_CLASS,
                     nil, nil, aStartupInfo, aProcessInfo);

  If n Then
    RunApp := aProcessInfo.hProcess
  Else
    RunApp := -1;
end;

procedure CloseProcessHandles;
begin
  CloseHandle(aProcessInfo.hThread);
  CloseHandle(aProcessInfo.hProcess);
end;


// Then you may call the RunApp function:

  hProcessHandle := RunApp(sPrintCmd);
  if hProcessHandle > 0 then
  begin
    WaitForSingleObject(hProcessHandle, _YOUR_WAIT_TIME_);
    CloseProcessHandles;;
  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