Programování ve Windows

různé vychytávky

[o úroveň výše]

Minimalizace celé aplikace z podřízeného okna, Rychlé kopírování souboru, Vícejazyčná aplikace, Práce se soubory, které mají asociaci, Práce se soubory, které mají asociaci, Variantní počet parametrů vstupujících do procedury


Minimalizace celé aplikace z podřízeného okna

Často se vyskytne potřeba minimalizovat celou aplikaci. Máte však zobrazeno jedno nebo více podřízených oken a při minimalizaci takovéhoto okna se zmenší pouze toto okno a zbytek aplikace zůstane tzv. "viset". Pro některé uživatele to může znamenat vážný problém. Jiný způsob je zrušit všechna podřízená okna a poté hlavní okno aplikace minimalizovat. Máte-li rozdělanou práci, představuje to opět problém.

Velmi elegantní řešení je použít do každého podřízeného okna níže uvedený kód.

Do privátní deklarace vložte tuto proceduru:

procedure WM_MyMessage(var Msg: TWMSYSCOMMAND); message WM_SYSCOMMAND;

Do implementační části vložte tuto odpovídající proceduru:

procedure TForm1.WM_MyMessage(var Msg: TWMSYSCOMMAND);
begin
  if Msg.CmdType = SC_MINIMIZE then
  Application.Minimize
else
  Inherited;
end;

To je vše.


Rychlé kopírování souboru

Procedure Kopiruj( Const ZdrojovySoubor, CilovySoubor: String );
Var Zdroj, Cil: TFileStream;

Begin
Zdroj := TFileStream.Create( ZdrojovySoubor, fmOpenRead );
try
  Cil := TFileStream.Create( CilovySoubor, fmOpenWrite or fmCreate );
  try
   Cil.CopyFrom(Zdroj, Zdroj.Size ) ;
  finally
   Cil.Free;
  end;
finally
Zdroj.Free;
end;
End;

Vícejazyčná aplikace

chcete-li programovat aplikaci a nechce se vám dělat varianta pro různé jazyky zvlášť, lze to vyřešit pomocí Resources, například takto:

unit French1;

interface

uses
  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics,
  Controls, Forms, Dialogs, StdCtrls, IniFiles;

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

var
  Form1: TForm1;
  StringIndex : Integer;
implementation

{$R *.DFM}

{$R MULTLANG.RES}

{ něco podobného by měl obsahovat resource soubor, všimněte
 si, že zlom je na pozici 8:
 1, "Attention"
 2, "No Condition definition selected!"
 3, "Always"
 4, "Cannot delete the 'always' condition."
 5, "Confirmation"
 6, "Delete the condition?"
 7, "Yes"
 8, "No"
 9, "Attention"
 10, "Pas de condition Selectionnée"
 11, "Toulours"
 12, "Ne peux effacer la condition 'Toujours'"
 13, "Confirmation"
 14, "Effacer cette condition?"
 15, "&Oui"
 16, "&Non"
}

procedure TForm1.FormActivate(Sender: TObject);
var
  {inifile : TIniFile; Optional}
  ProgramLanguage : String;
begin
  { natrdo nastavené , že chceme francouštinu }
   ProgramLanguage := 'fra';
  { Lepší je nastavení číst ze souboru (např:Win.INI)
   nebo z registru Windows:}
  {inifile := TInifile.Create('WIN.INI');
   ProgramLanguage := inifile.ReadString('intl', 'sLanguage',
   'enu');
   inifile.Free;}
  { Ve Win.ini můžete najít následující údaj v položce INTL

   dan = Danish
   nld = Dutch
   enu = English (American)
   eng = English (International)
   fin = Finnish
   fra = French
   frc = French Canadian
   deu = German
   isl = Icelandic
   ita = Italian
   nor = Norwegian
   ptg = Portuguese
   esp = Spanish
   esn = Spanish (Modern)
   sve = Swedish

}
   if ProgramLanguage = 'enu' then
   begin
      StringIndex := 0;
   end
   else
      if ProgramLanguage = 'fra' then
      begin
         StringIndex := 8;
      end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
   i,j,k : integer;
   DialogForm : tform;
begin
   Application.NormalizeTopMosts;
   {no Condition Selected!}
   DialogForm := CreateMessageDialog(LoadStr(StringIndex+2),
        mtWarning,[mbOK]);
   {Attention}
   DialogForm.caption := LoadStr(StringIndex + 1);
   DialogForm.showmodal;
   Application.RestoreTopMosts;
   {Cannot Delete the 'always' condition}
   DialogForm := CreateMessageDialog(LoadStr(StringIndex+4),
        mtWarning,[mbOK]);
   {Always}
   DialogForm.caption := LoadStr(StringIndex + 3);
   DialogForm.showmodal;
   Application.RestoreTopMosts;
   {Delete the condition?}
   DialogForm := CreateMessageDialog(LoadStr(StringIndex+6),
        mtInformation, [mbYes, mbNo]);
   {confirmation}
   DialogForm.caption := LoadStr(StringIndex + 5);
   for j := 0 to DialogForm.controlCount-1 do
   begin
      if DialogForm.controls[j] is tButton then
         with tButton(DialogForm.controls[j]) do
         begin
            if caption = '&Yes' then caption := 
               LoadStr(StringIndex+7);
            if caption = '&No' then caption := 
               LoadStr(StringIndex+8);
          end;
    end;
   DialogForm.showmodal;
end;

end.

Práce se soubory, které mají asociaci

Zde není co dodat...

unit UcShell;

{ Author: Michael Ax   www.axsystems.com
  Copyright (c) 1995..1997 Michael Ax.  All Rights Reserved.
  This source code is part of TPack from HREF Tools Corp.
  Obtain purchasing and additional information by sending an email to
  software@href.com (any subject, any message)...
  or visit us on the web at www.href.com/software/
}

interface

uses Classes, SysUtils, Windows, ShellApi, Forms;

{----------------------------------------------------------}

function WinExecutableName(const AssociatedFile:string):String;

procedure WinShellOpen(const AssociatedFile:string);
procedure WinShellPrint(const AssociatedFile:string);
procedure WinShellExecute(const Operation,AssociatedFile:string);

{---------------------------------------------------------------}

implementation

Const
  cStrBufSize= 80;

{---------------------------------------------------------------}


function WinExecutableName(const AssociatedFile:string):String;
//HINSTANCE FindExecutable(
//    LPCTSTR lpFile,   // pointer to string for filename
//    LPCTSTR lpDirectory,      // pointer to string for default directory
//    LPTSTR lpResult   // pointer to buffer for string for executable file
on return
//   );
begin
  SetLength(result,cStrBufSize); //ucshell
  FindExecutable(pchar(AssociatedFile),'',pchar(result));
  SetLength(result,strlen(pchar(result)));
end;

//

procedure WinShellExecute(const Operation,AssociatedFile:string);
var
  a1:string;
begin
  a1:=Operation;
  if a1='' then
    a1:='open';
  ShellExecute(
    application.handle			//hWnd: HWND
    ,pchar(a1)				//Operation: PChar
    ,pchar(AssociatedFile)		//FileName: PChar
    ,''						//Parameters: PChar
    ,''						//Directory: PChar
    ,SW_SHOWNORMAL		//ShowCmd: Integer
    );
//  GetLastErrorString(0);		//ucdialog
end;

procedure WinShellPrint(const AssociatedFile:string);
begin
  WinShellExecute('print',AssociatedFile);
end;

procedure WinShellOpen(const AssociatedFile:string);
begin
  WinShellExecute('open',AssociatedFile);
end;

{--------------------------------------------------------}
end.

MAPI a MS Exchange

Chcete-li pracovat s poštou, potřebujete znát tyto příkazy:

Příhlášení se do pošty

  MapiLogon(application.handle,nil,nil,mapi_use_default,0,@mapihandle)

poslání mejlu

  MapiSendMail(mapihandle, 0,MapiMessage,0, 0);

Před tímto příkazem musí být vyplněny pole SUBJECT, RECIP a NOTTEXT ve struktuře MapiMessage nebo se zpráva neodešle.


Variantní počet parametrů vstupujících do procedury

Původní autor: hallvard@falcon.no (Hallvard Vassbotn)
Do procedury
TestMultiPar můžete vstoupit s jakýmkoliv počtem a druhem parametrů. Vyhodnocení se dělá ve smyčce s proměnnou I

program VarPar;

{ A simple program to demonstrate use of type-safe variable number of
  parameters in Delphi.

  Written Mars 1995 by Hallvard Vassbotn
  hallvard@falcon.no
}

uses WinCrt, SysUtils;

{ These are predefined in System:
const
    vtInteger  = 0;
    vtBoolean  = 1;
    vtChar     = 2;
    vtExtended = 3;
    vtString   = 4;
    vtPointer  = 5;
    vtPChar    = 6;
    vtObject   = 7;
    vtClass    = 8;

  type
    TVarRec = record
      case Integer of
        vtInteger:  (VInteger: Longint; VType: Byte);
        vtBoolean:  (VBoolean: Boolean);
        vtChar:     (VChar: Char);
        vtExtended: (VExtended: PExtended);
        vtString:   (VString: PString);
        vtPointer:  (VPointer: Pointer);
        vtPChar:    (VPChar: PChar);
        vtObject:   (VObject: TObject);
        vtClass:    (VClass: TClass);
    end;
}

const
  TypeNames : array [vtInteger..vtClass] of PChar  =
   ('Integer', 'Boolean', 'Char', 'Extended', 'String',
    'Pointer', 'PChar', 'Object', 'Class');

{
According to the on-line docs (search for TVarRec), array of const
parameters are treated like array of TVarRec by the compiler.
This example will work just as well if you change the declaration of
TestMultiPar to:

  procedure TestMultiPar(const Args: array of TVarRec);

This would make the implementation of the routine cleaner (no absolute
variable declaration), but the interface would be less understandable
to the user of the routine.

The compiler looks at the parameters and builds the array directly on the
stack. For each item in the array it also sets the VType field to one
of the pre-defined constants vtXXXX. The actual value is always sent as
four bytes of information. For the Boolean and Char types, only the first
byte contains useful information.

So, go ahead, now you can write all those neat routines with variable
number of parameters - and still keep the type safety!
}

function PtrToHex(P: pointer): string;
begin
  Result := IntToHex(Seg(P^), 4) + ':' + IntToHex(Ofs(P^), 4);
end;

procedure TestMultiPar(const Args: array of const);
var
  ArgsTyped : array [0..$fff0 div sizeof(TVarRec)] of TVarRec absolute Args;
  i         : integer;
begin
  for i := Low(Args) to High(Args) do
    with ArgsTyped[i] do
    begin
      Write('Args[', i, '] : ', TypeNames[VType], ' = ');
      case VType of
        vtInteger:  writeln(VInteger);
        vtBoolean:  writeln(VBoolean);
        vtChar:     writeln(VChar);
        vtExtended: writeln(VExtended^:0:4);
        vtString:   writeln(VString^);
        vtPointer:  writeln(PtrToHex(VPointer));
        vtPChar:    writeln(VPChar);
        vtObject:   writeln(PtrToHex(Pointer(VObject)));
        vtClass:    writeln(PtrToHex(Pointer(VClass)));
      end;
    end;
end;

var
  MyObj : TObject; {toto je jen zkušební}
begin
  Writeln('Test of type-safe variable number of parameters in Delphi:');
  MyObj := TObject.Create;
  TestMultiPar([123, 45.67, PChar('ASCIIZ'), 'Hello, world!', true, 'X',
                @ShortDayNames, TObject, MyObj]);
  MyObj.Free;

  { To verify that the type-safety is used in the supplied formatting 
	routines,try this: }
  writeln(Format('%d', ['hi']));
  { The supplied parameter is not of the type expected. The '%d' format
 string signals that the parameter should be an integer value, but instead
 we send a string. At run-time this will generate a exception, and if you
 have enabled IDE-trapping of exceptions, Delphi will show you the 
 offending line. Using c-type sprintf funtions like this will result
 in undefined behaviour (read: system crash, GP or whatever) }
end.

[o úroveň výše]  


WEBovský počítadlo spočítalo, že si číslo počitadlo, které navštívilo od 17.října 1999 tyto stránky uložené na serveru Volny.cz
Tato stránka byla autorem naposledy editována 07.08.2007 13:27:24,
automatický update proveden 03.09.2007 22:23:44