Trucos Delphiraq

 

 

 

 

 

Vamos a ver una recopilacion de los mejores trucos para programar en Delphi. Si quieres que te incluyamos algun otro no dudes en enviarnoslo, entre todos podremos hacer un mundo mejor.

 

AÑADIR LOS PUNTOS DE MILES A UN NÚMERO

 

Como puedes observar el truco está en dar un formato de salida distinto al habitual

 

   procedure TForm1.Button2Click(Sender: TObject);

   var

      i:integer;

   begin

     i:=2538456;

     Label1.Caption:=FormatFloat('#,',i);

   end;

 
 

 

 

 

 

 

 

 

 

 

 


CALCULAR LA LETRA DEL NIF SEGÚN EL NÚMERO DEL DNI

function NIF(DNI: String): Char;

begin

  Result := Copy('TRWAGMYFPDXBNJZSQVHLCKET',StrToInt(DNI) mod 23+1,1)[1];

end;

 
 

 

 

 

 

 

 

 

 

 

 


COMPROBAR SI UN STRING TIENE UN NÚMERO

 

Intentamos convertir un String a un Entero, si no ocurre nada en el flujo de ejecución del programa, el String contiene un número, sino es asi salta la excepción y devolvemos false.

 

      function IsStrANumber(NumStr : string) : boolean;

      begin

        result := true;

        try

          StrToInt(NumStr);

        except

          result := false;

        end;

      end;

 
 

 

 

 

 

 

 

 

 

 

 

 

 


AGILIZAR LA CARGA DE TUS PROGRAMAS

 

No crees todos los forms de golpe, crea sólo el inicial, y desde el crea dinámicamente los que vayas a utilizar, sólo cuando los vayas a utilizar.

Es decir, en el IDE, en Project-Options tienes dos ventanas, una la de 'Autocreate forms' y otra, la de 'Available forms'. Pues pon sólo la principal en 'Autocreate forms'. Después, en el uses de la primera form, añades las units del resto de forms, y en el var de la primera form, declaras las variables TForm del resto de forms que vayas a crear.

 

Un ejemplo de Form1 que crea una Form2:

 

El uses de Form1:

 

uses

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

 

 
 

 

 

 

 

 

El var de Form1:

 

var

  Form1: TForm1;

  Form2: TForm2;

 
 

 

 

 

 

 

 

Y cuando quieras llamar a la Form2 desde Form1 usa:

 

procedure TForm1.Button1Click(Sender: TObject);

begin

  Form2:=TForm2.Create(self);

  Form2.Show;

end;

 

 
 

 

 

 

 

 

 

 

 

Si tras hacer todo esto, te sigue tardando mucho en cargar el primer form, puedes ponerle una Splash Screen (una pantalla inicial) en la que le pones el típico mensaje de 'cargando'.

 

DAR MAYOR PRIORIDAD A TU APLICACIÓN

 

  SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);

  SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);

 
 

 

 

 

 


RESTAURAR LA PRIORIDAD A TU APLICACIÓN

 

  SetPriorityClass(GetCurrentProcess, NORMAL_PRIORITY_CLASS);

  SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_NORMAL);

 
 

 

 

 

 

 

 


CAPTURAR LAS PROPIAS HOT-KEYS

 

Primero, pon la propiedad KeyPreview de la form a True. Entonces, haz algo como esto:

     procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;

       Shift: TShiftState);

     begin

       if (ssCtrl in Shift) and (chr(Key) in ['A', 'a']) then

         ShowMessage('Ctrl-A');

     end;

 
 

 

 

 

 

 

 

 

 

 

 

En el ejemplo, capturamos el Ctrl-A

 

CERRAR OTRA APLICACIÓN DESDE LA TUYA

 

Es fácil: envianadole un mensaje WM_CLOSE.

Por ejemplo, cerrar la calculadora de Windows:

 

 

procedure TForm1.Button1Click(Sender: TObject);

var

   Mango:integer;

begin

  Mango:=FindWindow(nil,'Calculadora');

  if mango=0

    then ShowMessage('No encuentro esa aplicacion')

    else SendMessage(Mango,WM_CLOSE,0,0);

end;

 
 

 

 

 

 

 

 

 

 

 

 

 

Para cerrar cualquier otra aplicacion, deberias saber o bien su ClassName o bien el titulo de la ventana. Este invento te dirá ambos de todas las aplicaciones que tengas rulando:

 

            -Crea una form y pon un TMemo (Memo1) y un TButton (Button1) en ella.

            -En el private de la declaracion de la form pon:

 

  private

    { Private declarations }

    WindowList1 : TList;

 

 
 

 

 

 

 

            -Y en el OnCLick del Button1 pon este código:

 

procedure TForm1.Button2Click(Sender: TObject);

var

 TopWindow   : HWND;

 WinName,

 WinClass    : array[0..80] of Char;

 x           : Integer;

 NoError     : Boolean;

 function GetAllWindows(Handle: HWND;

          NotUsed: Pointer): Boolean; stdcall;

 begin

   Result := True;

   Form1.WindowList1.Add(Pointer(Handle));

 end;

begin

  TopWindow   := Handle;

  WindowList1 := TList.Create;

            try

              NoError := EnumWindows(@GetAllWindows,

                                     Longint(@TopWindow));

 

              if not NoError then

                Exit;

 

              for x := 0 to WindowList1.Count - 1 do

              begin

 

                GetWindowText(HWND(WindowList1[x]),

                              WinName,

                              SizeOf(WinName) - 1);

 

                GetClassName(HWND(WindowList1[x]),

                             WinClass,

                             SizeOf(WinName) - 1);

 

                memo1.Lines.add('Titulo:'+Winname+'-Clase:'+WinClass);

              end;

            finally

              WindowList1.Free;

            end;

end;

 

 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Y tendras una lista de las tareas ejecutandose, con su titulo y nombre de clase.

 

 

CERRAR UNA APLICACIÓN SABIENDO EL NOMBRE DE SU EJECUTABLE

 

Añade TLHelp32 en el uses de tu form

 

procedure TForm1.Button2Click(Sender: TObject);

 

  function CierraExe (FicheroExe:string):boolean;

 

    function SacaExe(MangoW:HWND):string;

    {Obtiene el EXE de una tarea}

    {get EXE of a task}

    var

      Datos    :TProcessEntry32;

      hID       :DWord;

      Snap    : Integer;

    begin

      GetWindowThreadProcessId(MangoW,@hID);

      Snap:=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);

      try

        Datos.dwSize:=SizeOf(Datos);

        if(Process32First(Snap,Datos))then

        begin

          repeat

            if Datos.th32ProcessID=hID then

            begin

              Result:=StrPas(Datos.szExeFile);

              Break;

            end;

          until not(Process32Next(Snap,Datos));

        end;

      finally

        Windows.CloseHandle(Snap);

      end;

    end;

 

 

   function ObtieneVentanas(Mango: HWND;

            ACerrar: Pointer): Boolean; stdcall;

   begin

     Result := True;

     {Mango es el handle de la tarea encontrada}

     {Si es el .EXE buscado, lo cierra}

     if SacaExe(Mango)=UpperCase( String(ACerrar^) )then

     begin

       SendMessage(Mango,WM_Close,0,0);

       String(Acerrar^):='CERRADO';

     end;

   end;

 

 

 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

begin

    EnumWindows( @ObtieneVentanas, Integer(@FicheroExe) );

    Result:=(FicheroExe='CERRADO');

  end;

 

begin

 if CierraExe('C:\WINDOWS\NOTEPAD.EXE')

   then ShowMessage ('Cerrado/Closed')

   else ShowMessage ('No Encontrado/not Found');

end;

 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Cambiado la definición de tipo de hID de integer a DWord.

 

HACER QUE UN ENTER FUNCIONE COMO UN TABULADOR

 

Coloca este código en el evento OnKeyPress de tu form:

begin

  if Key = #13 then                          

   begin

      Key := #0;                                

      Perform(WM_NEXTDLGCTL, 0, 0);             

  end

end;

 

 
 

 

 

 

 

 

 

 

 

 

 

Esto hará que te muevas entre los Edits, botones, etc con el ENTER además de con el

TAB. Si tu form SI tiene un control DBGrid, igual te guste más éste codigo:

{ Este es el manejador de evento de OnKeyPress de tu form }

{ Debes poner la propiedad KeyPreview de la form a true}

 

begin

  if Key = #13 then                                                 { if it's an enter key }

    if not (ActiveControl is TDBGrid) then begin       { if not on a TDBGrid }

      Key := #0;                                                        { eat enter key }

      Perform(WM_NEXTDLGCTL, 0, 0);                 { move to next control }

    end

    else if (ActiveControl is TDBGrid) then                { if it is a TDBGrid }

 

      with TDBGrid(ActiveControl) do

        if selectedindex < (fieldcount -1) then             { increment the field }

          selectedindex := selectedindex +1

        else

          selectedindex := 0;

end;

 

 
 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

En ambos casos, recuerda poner la propiedad KeyPreview de la form a true.

 

HINTS CON UN COLOR DISTINTO (CUADROS DE AYUDA)

 

Para conseguirlo, crearemos nuestro propio descendiente de THintWindow, en el que

añadiremos algo al método Create para que cambie el font a nuestro gusto.

Vamos con el código:

 

-Definimos nuestro descendiente de THintWindow, es decir, ponemos esto en el