2006. október 14., szombat
How to paint a moving progress bar using a background thread
Problem/Question/Abstract:
I query several tables and display records in a TDBGrid . However, due to the size of the tables and joins, it takes a while for the query to execute. Is there any way to show a progress bar with a timer that increments the position but continues to work while the query is being executed.
Answer:
A progress bar would not be an ideal choice since you cannot determine up front how long the query will take, so you do not know the range the progress bar has to cover. A simple kind of animation that tells the user basically only that the application is not hung would be more appropriate. One could do such a thing in a secondary thread but it would have to be done using the plain Windows API and no Synchronize calls (since the main thread is blocked in the BDE call). Here is an example:
unit anithread;
interface
uses
Classes, Windows, Controls, Graphics;
type
TAnimationThread = class(TThread)
private
{ Private declarations }
FWnd: HWND;
FPaintRect: TRect;
FbkColor, FfgColor: TColor;
FInterval: Integer;
protected
procedure Execute; override;
public
constructor create(
paintsurface: TWinControl; {Control to paint on}
paintrect: TRect; {area for animation bar}
bkColor, barcolor: TColor; {colors to use}
interval: Integer {wait in msecs between paints}
);
end;
implementation
constructor TAnimationThread.create(paintsurface: TWinControl;
paintrect: TRect; bkColor, barcolor: TColor; interval: Integer);
begin
inherited Create(true);
FWnd := paintsurface.Handle;
FPaintRect := paintrect;
FbkColor := bkColor;
FfgColor := barColor;
FInterval := interval;
FreeOnterminate := True;
Resume;
end;
procedure TAnimationThread.Execute;
var
image: TBitmap;
DC: HDC;
left, right: Integer;
increment: Integer;
imagerect: TRect;
state: (incRight, incLeft, decLeft, decRight);
begin
Image := TBitmap.Create;
try
with Image do
begin
Width := FPaintRect.Right - FPaintRect.Left;
Height := FPaintRect.Bottom - FPaintRect.Top;
imagerect := Rect(0, 0, Width, Height);
end;
left := 0;
right := 0;
increment := imagerect.right div 50;
state := Low(State);
while not Terminated do
begin
with Image.Canvas do
begin
Brush.Color := FbkColor;
FillRect(imagerect);
case state of
incRight:
begin
Inc(right, increment);
if right > imagerect.right then
begin
right := imagerect.right;
Inc(state);
end;
end;
incLeft:
begin
Inc(left, increment);
if left >= right then
begin
left := right;
Inc(state);
end;
end;
decLeft:
begin
Dec(left, increment);
if left <= 0 then
begin
left := 0;
Inc(state);
end;
end;
decRight:
begin
Dec(right, increment);
if right <= 0 then
begin
right := 0;
state := incRight;
end;
end;
end;
Brush.Color := FfgColor;
FillRect(Rect(left, imagerect.top, right, imagerect.bottom));
end;
DC := GetDC(FWnd);
if DC <> 0 then
try
BitBlt(DC, FPaintRect.Left, FPaintRect.Top, imagerect.right, imagerect.bottom,
Image.Canvas.handle, 0, 0, SRCCOPY);
finally
ReleaseDC(FWnd, DC);
end;
Sleep(FInterval);
end;
finally
Image.Free;
end;
InvalidateRect(FWnd, nil, true);
end;
end.
Usage:
Place a TPanel on a form, size it as appropriate. Create an instance of the TanimationThread call like this:
procedure TForm1.Button1Click(Sender: TObject);
var
ani: TAnimationThread;
r: TRect;
begin
r := panel1.clientrect;
InflateRect(r, -panel1.bevelwidth, -panel1.bevelwidth);
ani := TanimationThread.Create(panel1, r, panel1.color, clBlue, 25);
Button1.Enabled := false;
Application.ProcessMessages;
Sleep(30000); {replace with query.Open or such}
Button1.Enabled := true;
ani.Terminate;
ShowMessage('Done');
end;
2006. október 13., péntek
How to set the date stamp of a file equal to the date stamp of another
Problem/Question/Abstract:
How to set the date stamp of a file equal to the date stamp of another
Answer:
Just use the following function, which takes two strings representing full DOS path/ file names. The file who's date you wish to set is the second parameter, and the date you wish to set it to is given by the file in the first parameter.
procedure CopyFileDate(const Source, Dest: string);
var
SourceHand, DestHand: word;
begin
SourceHand := FileOpen(Source, fmOutput); { open source file }
DestHand := FileOpen(Dest, fmInput); { open dest file }
FileSetDate(DestHand, FileGetDate(SourceHand)); { get / set date }
FileClose(SourceHand); { close source file }
FileClose(DestHand); { close dest file }
end;
2006. október 12., csütörtök
Get the Windows Start Menu folder location and name
Problem/Question/Abstract:
How to get the Start Menu folder location in Windows regardless of the OS (WinNT Wks, WinNT Srv, Win95, Win98)?
Answer:
Solve 1:
procedure FreePidl(pidl: PItemIDList);
var
allocator: IMalloc;
begin
if Succeeded(SHGetMalloc(allocator)) then
begin
allocator.Free(pidl);
{$IFDEF VER90}
allocator.Release;
{$ENDIF}
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
pidl: PItemIDList;
buf: array[0..MAX_PATH] of Char;
begin
if Succeeded(ShGetSpecialFolderLocation(Handle, CSIDL_STARTMENU, pidl)) then
begin
if ShGetPathfromIDList(pidl, buf) then
ShowMessage(buf);
FreePIDL(pidl);
end;
end;
Needs ShlObj in the Uses clause.
Solve 2:
To obtain the name of the Windows\Start Menu\Program directory on a system, use code like this:
function GetSpecialDir(Index: Integer): string;
var
S: string;
IDL: PItemIDList;
begin
Result := '';
if Succeeded(SHGetSpecialFolderLocation(0, Index, IDL)) then
begin
SetLength(S, MAX_PATH);
if Succeeded(SHGetPathFromIDList(IDL, PChar(S))) then
Result := PChar(S);
end;
end;
You call it with code like:
ProgDir := GetSpecialDir(CSIDL_PROGRAMS);
The CSIDL_ identifiers are specified in ShlObj.pas, so are the SHGetSpecialFolderLocation and SHGetPathFromIDList functions.
Solve 3:
Here is an example to get the startup folder:
{ ... }
var
idRoot: PItemIDList;
Buf: array[1..MAX_PATH] of Char;
begin
StartupFolder := '';
try
if SHGetSpecialFolderLocation(Handle, CSIDL_STARTUP, idRoot) = NOERROR then
begin
FillChar(Buf, SizeOf(Buf), #32);
SHGetPathFromIDList(idRoot, PChar(@Buf));
SetString(StartupFolder, PChar(@Buf), Length(Buf));
StartupFolder := Trim(StartupFolder) + '\';
end;
except
end;
end;
{ ... }
2006. október 11., szerda
Preventing a user from closing a window except at shutdown or restart
Problem/Question/Abstract:
How to oreventing a user from closing a window except at shutdown or restart
Answer:
We all know how to prevent a window from closing: Simply write event code for the OnCloseQuery event and set CanClose to False. Once that's done, no matter what a user presses, the window won't close. Here's some code:
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := False;
end;
But what if you wanted to be able to close a window only when you reboot the machine? With the scenario above, that would be impossible. Fortunately though, there is a solution, and it resides in the windows message WM_QUERYENDSESSION.
WM_QUERYENDSESSION is generated by Windows when the OS is resetting: Either at a shutdown or a restart. Using this message, we can set a boolean flag variable and interrogate its value in OnCloseQuery to allow us to close the window and reset the operating system. Look at the unit code below:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes,
Graphics, Controls, Forms, Dialogs;
type
TForm1 = class(TForm)
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
procedure WMQueryEndSession(var Message: TWMQueryEndSession);
message WM_QUERYENDSESSION;
public
WindowsClosing: Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
WindowsClosing := False;
end;
procedure TForm1.WMQueryEndSession(var Message: TWMQUERYENDSESSION);
begin
WindowsClosing := True;
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := WindowsClosing;
end;
end.
As you can see, I've created a public variable called WindowsClosing. When WM_QUERYENDSESSION fires, it sets the variable to True. Then in OnCloseQuery, CanClose is set to the value of WindowsClosing. Notice that I set WindowsClosing to False in OnCreate. This is purely for initialization purposes to make sure that previous attempts to close the window are foiled.
2006. október 10., kedd
How to implement a Query by Form service for a TDBGrid
Problem/Question/Abstract:
How to implement a Query by Form service for a TDBGrid
Answer:
Here is a Delphi unit for a modal dialog to support Query By Form (QBF) for DbGrid components which receive data from Table components (not Query components). The lack of this as a built-in feature makes it harder for Delphi to compete with more resource-intensive tools like Oracle Forms. This unit is not as powerful as the built-in QBF features of Oracle Forms, but it does fill a significant gap in functionality.
unit Db_QBF;
{This unit provides a basic but effective Query By Form service for database access applications written using Borland Delphi. This unit also provides a similar Sort By Form service.
The Query By Form service displays a modal dialog box with a StringGrid of searchable fields, taken from the calling DbGrid. The user may enter an exact search value for any number of fields, and may use drag and drop to rearrange the sort order of the fields. (Only the fields that contain search values are relevant to the sort.) When the user clicks the dialog's OK button, this unit modifies the calling DbGrid's IndexFieldNames property, applies a search range (of exact values), and refreshes the data. If the user leaves all search values empty, this unit clears the calling DbGrid's IndexFieldNames property, clears the search range, and refreshes the data.
The Sort By Form service works in a similar manner, except that it does not accept search values from the user. The user drags and drops the field sort order, then clicks the OK button. This unit modifies the calling DbGrid's IndexFieldNames property, clears the search range, and refreshes the data.
Create the corresponding dialog form using the New Form action, selecting a Standard Dialog Box. Place a StringGrid on the form (as found in the Additional tab of the component toolbar. Set the StringGrid's Height to 161 and its Width to 305. Finally, replace the new form's .PAS source with this unit.}
interface
uses
WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, ExtCtrls, Grids, DBGrids;
{The following two procedures provide the mechanism for accessing the services of this unit. Have a button or menu item on the calling form call one of these procedures, passing the DbGrid as the argument. (Remember to add "uses Db_QBF;" to the calling form's implementation section.). Restriction: The DbGrid must reference a DataSource that, in turn, references a DataSet that is a Table. This unit does not support a DataSet that is a Query, since it has no IndexFieldNames property.}
procedure QueryByForm(grid: TDbGrid);
procedure SortByForm(grid: TDbGrid);
type
TdlgQBF = class(TForm)
OKBtn: TBitBtn;
CancelBtn: TBitBtn;
HelpBtn: TBitBtn;
gridQBF: TStringGrid;
procedure OKBtnClick(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dlgQBF: TdlgQBF;
implementation
uses
Dialogs, Db, DbTables;
{$R *.DFM}
const
qbfRowHeight = 16;
qbfColWidth = 150;
qbfFieldLabel = ' Field ';
qbfValueLabel = ' Value ';
qbfQueryCaption = ' Query for Table ';
qbfSortCaption = ' Sort Order for Table ';
var
{Remember some things for use by the QBF dialog's OK button}
CallingGrid: TDbGrid;
CallingMode: (modeQuery, modeSort);
procedure SetupAndShowForm;
{ Called by the two exported procedures }
var
i, j, n: integer;
tbl: TTable;
f: TField;
begin
n := CallingGrid.FieldCount;
if n <= 0 then
begin
{ Exceptions may be raised instead of showing messages }
MessageDlg('Db_QBF unit called for a DbGrid without any Fields', mtWarning,
[mbOK], 0);
end
else if CallingGrid.DataSource = nil then
begin
MessageDlg('Db_QBF unit called for a DbGrid without a DataSource', mtWarning,
[mbOK], 0);
end
else if CallingGrid.DataSource.DataSet = nil then
begin
MessageDlg('Db_QBF unit called for a DbGrid with a DataSource without a DataSet',
mtWarning, [mbOK], 0);
end
else if not (CallingGrid.DataSource.DataSet is TTable) then
begin
MessageDlg('Db_QBF unit called for a DbGrid with a DataSource that
is not a Table', mtWarning, [mbOK], 0);
end
else
with dlgQBF.gridQBF do
begin
{These properties can also be set once at design time}
DefaultRowHeight := qbfRowHeight;
Scrollbars := ssVertical;
ColCount := 2;
{Even the Sort service needs a dummy second column}
{These properties must be set at run time}
RowCount := Succ(n);
Cells[0, 0] := qbfFieldLabel;
Options := Options + [goRowMoving];
tbl := TTable(CallingGrid.DataSource.DataSet);
if CallingMode = modeQuery then
begin
dlgQBF.Caption := qbfQueryCaption + tbl.TableName;
Cells[1, 0] := qbfValueLabel;
Options := Options + [goEditing]; { Allow user to enter values }
DefaultColWidth := qbfColWidth;
end
else
begin
dlgQBF.Caption := qbfSortCaption + tbl.TableName;
Cells[1, 0] := ''; {Dummy "value" column to allow fixed "field" column}
Options := Options - [goEditing]; {User just reorders the rows}
DefaultColWidth := (2 * qbfColWidth); {Shove aside dummy 2nd column}
end;
j := 0; {Actual number of fields shown to user}
for i := 1 to n do
begin
f := CallingGrid.Fields[Pred(i)];
if f.DataType in [ftBlob, ftBytes, ftGraphic, ftMemo, ftUnknown, ftVarBytes]
then
RowCount := Pred(RowCount) {Ignore unsearchable fields}
else
begin
Inc(j);
Cells[0, j] := f.FieldName;
Cells[1, j] := ''; {Empty search value}
end;
end;
dlgQBF.HelpBtn.Visible := False; {We haven't implemented Help}
dlgQBF.ShowModal;
end;
end;
procedure QueryByForm(Grid: TDbGrid);
begin
CallingGrid := Grid; {Save for use by OK button}
CallingMode := modeQuery;
SetupAndShowForm;
end;
procedure SortByForm(Grid: TDbGrid);
begin
CallingGrid := Grid; {Save for use by OK button}
CallingMode := modeSort;
SetupAndShowForm;
end;
procedure TdlgQBF.CancelBtnClick(Sender: TObject);
begin
{Just dismiss the dialog, without making changes to the calling grid}
dlgQBF.Hide;
end;
procedure TdlgQBF.OKBtnClick(Sender: TObject);
var
flds, sep, val: string;
i, n, nfld: integer;
begin
flds := ''; { List of fields separated by ';'}
sep := ''; { Becomes ';' after the 1st field is appended }
nfld := 0; { Number of fields in the list }
with dlgQBF.gridQBF do
begin
n := Pred(RowCount);
if n > 0 then
for i := 1 to n do
begin
val := Cells[1, i]; { The user-entered search value (if any) }
if (CallingMode = modeSort) or (val < > '') then
begin
flds := flds + sep + Cells[0, i];
sep := ';';
nfld := Succ(nfld);
end;
end;
with CallingGrid.DataSource.DataSet as TTable do
begin
IndexFieldNames := flds;
if (CallingMode = modeSort) or (flds = '') then
begin
CancelRange;
end
else
begin
SetRangeStart;
for i := 1 to n do
begin
val := Cells[1, i];
if val <> '' then
begin
FieldByName(Cells[0, i]).AsString := val;
end;
end;
SetRangeEnd; {Set range end to match range start}
for i := 1 to n do
begin
val := Cells[1, i];
if val <> '' then
begin
FieldByName(Cells[0, i]).AsString := val;
end;
end;
ApplyRange;
end;
Refresh;
end;
end;
dlgQBF.Hide;
end;
end.
2006. október 9., hétfő
How to detect a CR / LF in a TRichEdit
Problem/Question/Abstract:
I need to determine where there are CR/LF's in a TRichEdit. Here's the problem. I need to use the TRichEdit to take pretty much just plain text. I am using the TRichEdit instead of the TMemo because it handles end-of-line spaces much better. When I save the text, I need to save it in a proprietary text format. So when I encounter a CRLF, I need to place a "/p" combination at the end of the text line.
Answer:
procedure SaveTextWithParagraphMarkers(const filename, Text, marker: string);
var
fs: TFilestream;
S: string;
begin
S := Stringreplace(text, #13#10, marker, [srReplaceAll]);
fs := TFilestream.Create(filename, fmCreate);
try
fs.WriteBuffer(S[1], Length(S));
finally
fs.Free
end;
end;
SaveTextWithParagraphMakers(filename, richedit1.text, '/p'#13#10);
2006. október 8., vasárnap
Set the selected block to upper case/lower case
Problem/Question/Abstract:
Set the selected block to upper case/lower case
Answer:
I constantly forget this shortcut, particularly the one how to set the selected block to lower case.
Since it is hard to find in the online help, here it is as a reminder for myself:
press Ctrl+K then release and press O block lower case
press Ctrl+K then release and press N block upper case
(I don't know whether this works in editor layouts other than IDE classic.)
2006. október 7., szombat
Looking for text in any part of a field
Problem/Question/Abstract:
A function to search text in part of a field of any dataset
Answer:
The following function searches for text in any part of a field of any dataset (it can be for example a TTable, TQuery, TADOTable, TADOQuery, TIBTable, TIBQuery, etc.)
type
TLocateStrOption = (loCaseSensitive, loContinue);
TLocateStrOptions = set of TLocateStrOption;
function LocateStr(Dataset: TDataset; Field: TField; Str: string;
LocateOptions: TLocateStrOptions): boolean;
// Searches text in any part of a dataset field. The search can be
// case sensitive (option loCaseSensitive) and can start from the
// beginning or from the current record (option loContinue).
//
// Returns True if the string was found (the dataset is positioned
// in that record) and False otherwise (the dataset is left in EOF)
var
ControlsDisabled: boolean;
begin
ControlsDisabled := Dataset.ControlsDisabled;
if not ControlsDisabled then
Dataset.DisableControls;
try
if loContinue in LocateOptions then
begin
if not Dataset.Eof then
Dataset.Next;
end
else
Dataset.First; // Start from the beginning
if not (loCaseSensitive in LocateOptions) then
Str := UpperCase(Str);
while not Dataset.Eof do
begin
if loCaseSensitive in LocateOptions then
begin
if Pos(Str, Field.AsString) <> 0 then
break;
end
else
begin
if Pos(Str, UpperCase(Field.AsString)) <> 0 then
break;
end;
Dataset.Next;
end;
Result := Dataset.Eof;
finally
if not ControlsDisabled then
Dataset.EnableControls;
end;
end;
Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php
2006. október 6., péntek
Sort a TListView by numerical values
Problem/Question/Abstract:
My TListView is populated with file names in the first column and their sizes in the second column. To sort the data in the columns I use certain code. Now I would like the second column sorted not by Ansi values, where 822 is greater than 1000, but by numerical values. The second column must behave like the first, which means that the first click sorts the values ascending and the next click sorts them descending. Can anyone help me?
Answer:
Start a new project, and drop a ListView on the form. Replace all of the unit's code with code listed below. Set the ListView1's OnColumnClick Event to point to the ListView1ColumnClick in the code and link the form's OnCreate to the FormCreate. Run the program. Every time you click on the "Column 2" header, the column will sort in the opposite order. Note, if you click too quick, it'll be considered a double click, and it's not set up for that. Also, if you click on Column 1's header, it'll sort alphabetically.
unit Unit1;
{$O-}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls,
StdCtrls;
type
TForm1 = class(TForm)
ListView1: TListView;
procedure FormCreate(Sender: TObject);
procedure ListView1ColumnClick(Sender: TObject; Column: TListColumn);
private
NameSortOrder, SizeSortOrder: integer;
public
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
ListItem: TListItem;
begin
Randomize;
NameSortOrder := -1;
SizeSortOrder := -1;
with ListView1 do
begin
Align := alClient;
ViewStyle := vsReport;
with Columns.Add do
begin
Caption := 'Column 1';
width := 90;
end;
with Columns.Add do
begin
Caption := 'Column 2';
width := 90;
Alignment := taRightJustify;
end;
for i := 1 to 20 do
begin
ListItem := ListView1.Items.Add;
with ListItem do
begin
caption := format('FileName %2d', [i]);
SubItems.add(Format('%3.6n', [random]));
end;
end;
end;
end;
function SizeCustomSort(Item1, Item2: TListItem; ParamSort: integer): integer;
stdcall;
var
R1, R2: real;
code: Integer;
begin
val(Item1.SubItems.Strings[0], R1, code); {ignore code}
val(Item2.SubItems.Strings[0], R2, code);
if R1 > R2 then
result := ParamSort
else if R1 < R2 then
result := -ParamSort
else
result := 0;
end;
procedure TForm1.ListView1ColumnClick(Sender: TObject; Column: TListColumn);
begin
if Column.Index = 1 then
begin
ListView1.CustomSort(@SizeCustomSort, SizeSortOrder);
SizeSortOrder := SizeSortOrder * -1; {reverse the next sort order}
end
else
begin
ListView1.SortType := stText;
ListView1.AlphaSort;
end;
end;
end.
2006. október 5., csütörtök
Another option to execute system commands
Problem/Question/Abstract:
When you want to execute some command you just call WinExec. But if you want to execute some system command like 'dir *.*' or even execute an old DOS application, WinExec by itself just doesn't give all you want.
Answer:
The solution here it's by running your commands trought the COMSPEC. This is, COMPSPEC it's an environment variable that on Windows NT and 2000 returns the path to CMD.EXE and on Windows 9x returns the path to COMMAND.COM.
While I tested all this article code with Windows 2000 it can probably run also in Windows 9x (I think).
If you go to 'Command Prompt' and write the following you'll get a description of a various number of options that you can use to run a command (or a batch of commands in a single command line):
Starts a new instance of the Windows 2000 command interpreter
CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
[[/S] [/C | /K] string]
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
/S Modifies the treatment of string after /C or /K (see below)
/Q Turns echo off
/D Disable execution of AutoRun commands from registry (see below)
/A Causes the output of internal commands to a pipe or file to be ANSI
/U Causes the output of internal commands to a pipe or file to be
Unicode
/T:fg Sets the foreground/background colors (see COLOR /? for more info)
/E:ON Enable command extensions (see below)
/E:OFF Disable command extensions (see below)
/F:ON Enable file and directory name completion characters (see below)
/F:OFF Disable file and directory name completion characters (see below)
/V:ON Enable delayed environment variable expansion using c as the
delimiter. For example, /V:ON would allow !var! to expand the
variable var at execution time. The var syntax expands variables
at input time, which is quite a different thing when inside of a FOR
loop.
/V:OFF Disable delayed environment expansion.
Note that multiple commands separated by the command separator '&&' are accepted for string if surrounded by quotes. Also, for compatibility reasons, /X is the same as /E:ON, /Y is the same as /E:OFF and /R is the same as /C. Any other switches are ignored.
If /C or /K is specified, then the remainder of the command line after the switch is processed as a command line, where the following logic is used to process quote (") characters:
1. If all of the following conditions are met, then quote characters
on the command line are preserved:
- no /S switch
- exactly two quote characters
- no special characters between the two quote characters,
where special is one of: &<>()@^|
- there are one or more whitespace characters between the
the two quote characters
- the string between the two quote characters is the name
of an executable file.
2. Otherwise, old behavior is to see if the first character is
a quote character and if so, strip the leading character and
remove the last quote character on the command line, preserving
any text after the last quote character.
If /D was NOT specified on the command line, then when CMD.EXE starts, it
looks for the following REG_SZ/REG_EXPAND_SZ registry variables, and if
either or both are present, they are executed first.
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
Command Extensions are enabled by default. You may also disable extensions for a particular invocation by using the /E:OFF switch. You can enable or disable extensions for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDT32.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\EnableExtensions
to either 0x1 or 0x0. The user specific setting takes precedence over the machine setting. The command line switches take precedence over the registry settings.
The command extensions involve changes and/or additions to the following
commands:
DEL or ERASE
COLOR
CD or CHDIR
MD or MKDIR
PROMPT
PUSHD
POPD
SET
SETLOCAL
ENDLOCAL
IF
FOR
CALL
SHIFT
GOTO
START (also includes changes to external command invocation)
ASSOC
FTYPE
To get specific details, type commandname /? to view the specifics.
Delayed environment variable expansion is NOT enabled by default. You can enable or disable delayed environment variable expansion for a particular invocation of CMD.EXE with the /V:ON or /V:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDT32.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\DelayedExpansion
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\DelayedExpansion
to either 0x1 or 0x0. The user specific setting takes precedence over the machine setting. The command line switches take precedence over the registry settings.
If delayed environment variable expansion is enabled, then the exclamation
character can be used to substitute the value of an environment variable
at execution time.
File and Directory name completion is NOT enabled by default. You can enable or disable file name completion for a particular invocation of CMD.EXE with the /F:ON or /F:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDT32.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar
with the hex value of a control character to use for a particular function (e.g. 0x4 is Ctrl-D and 0x6 is Ctrl-F). The user specific settings take precedence over the machine settings. The command line switches take precedence over the registry settings.
If completion is enabled with the /F:ON switch, the two control characters used are Ctrl-D for directory name completion and Ctrl-F for file name completion. To disable a particular completion character in the registry, use the value for space (0x20) as it is not a valid control character.
Completion is invoked when you type either of the two control characters. The completion function takes the path string to the left of the cursor appends a wild card character to it if none is already present and builds up a list of paths that match. It then displays the first matching path. If no paths match, it just beeps and leaves the display alone. Thereafter, repeated pressing of the same control character will cycle through the list of matching paths. Pressing the Shift key with the control character will move through the list backwards. If you edit the line in any way and press the control character again, the saved list of matching paths is discarded and a new one generated. The same occurs if you switch between file and directory name completion. The only difference between the two control characters is the file completion character matches both file and directory names, while the directory completion character only matches directory names.
If file completion is used on any of the built in directory commands (CD, MD or RD) then directory completion is assumed.
The completion code deals correctly with file names that contain spaces or other special characters by placing quotes around the matching path.
Also, if you back up, then invoke completion from within a line, the text to the right of the cursor at the point completion was invoked is discarded.
and it's this option that will let you run commands without the disadvantage of using batch files.
With this article you'll also have an attached project sample containing an unit (SysCommand.pas) that implements a small component. The best thing you can do it's look at the attached sample, anyway here it is a small test sample:
var
FSysCommand: TSysCommand;
begin
FSysCommand := TSysCommand.Create(Self);
FSysCommand.WhenDone := cwdRemain;
FSysCommand.WindowTitle := 'This is a test';
FSysCommand.BkColor := cclBtWhite;
FSysCommand.FgColor := cclLtRed;
FSysCommand.CmdsList.Add('echo Now I will list your windows directory files.');
FSysCommand.CmdsList.Add('pause');
FSysCommand.CmdsList.Add('dir "c:\windows\*.*" /s');
FSysCommand.Execute;
as you can see, it's easy and simple to run a batch of commands throught the
Command Prompt.
= = SysCommand.pas = =
unit SysCommand;
// by Fernando J.A. Silva (magico@galaxycorp.com) 2001/08/24
interface
uses
Classes;
type
TCmdWhenDone = (
cwdClose { /C or /R },
// Carries out the command specified by string and then terminates
cwdRemain { /K } // Carries out the command specified by string but remains
);
TCmdAutoRunCmds = (
carDefault,
carDisable { /D } // Disable execution of AutoRun commands from registry
);
// if carDisable was NOT specified, then when the command is launched, it
// looks for the following REG_SZ/REG_EXPAND_SZ registry variables, and if
// either or both are present, they are executed first.
//
// HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
// and/or
// HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
TCmdOutputType = (
cotANSI { /A },
// Causes the output of internal commands to a pipe or file to be ANSI
cotUnicode { /U } // Causes the output of internal commands to a pipe or file to be Unicode
);
TCmdColor = (cclNone, cclBlack {0}, cclBlue {1}, cclGreen {2}, cclAqua {3}, cclRed
{4},
cclPurple {5}, cclYellow {6}, cclWhite {7}, cclGray {8}, cclLtBlue {9},
cclLtGreen {A}, cclLtAqua {B}, cclLtRed {C}, cclLtPurple {D}, cclLtYellow {E},
cclBtWhite {F});
TCmdExtensions = (
cexDefault,
cexON, {/E:ON or /X } // Enable command extensions
cexOFF {/E:OFF or /Y } // Disable command extensions
);
// Command Extensions are enabled by default. You may also disable extensions
// for a particular invocation by using the cexOFF. You can enable or disable
// extensions for all invocations of CMD.EXE on a machine and/or user logon
// session by setting either or both of the following REG_DWORD values in the
// registry using REGEDT32.EXE:
//
// HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions
// and/or
// HKEY_CURRENT_USER\Software\Microsoft\Command Processor\EnableExtensions
//
// to either 0x1 or 0x0. The user specific setting takes precedence over
// the machine setting. The command line switches take precedence over the
// registry settings.
TSysCommand = class(TComponent)
private
FOutputType: TCmdOutputType;
FAutoRunCmds: TCmdAutoRunCmds;
FCmdExtensions: TCmdExtensions;
FWhenDone: TCmdWhenDone;
FBkColor: TCmdColor;
FFgColor: TCmdColor;
FWindowTitle: string;
FCmdsList: TStringList;
function GetParamsString: string;
procedure GetInternalCmdsList(var AList: TStringList);
function GetCommandsString: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: Boolean;
published
property OutputType: TCmdOutputType read FOutputType write FOutputType;
property AutoRunCmds: TCmdAutoRunCmds read FAutoRunCmds write FAutoRunCmds;
property CmdExtensions: TCmdExtensions read FCmdExtensions write FCmdExtensions;
property WhenDone: TCmdWhenDone read FWhenDone write FWhenDone;
property BkColor: TCmdColor read FBkColor write FBkColor;
property FgColor: TCmdColor read FFgColor write FFgColor;
property WindowTitle: string read FWindowTitle write FWindowTitle;
property CmdsList: TStringList read FCmdsList write FCmdsList;
end;
implementation
uses
Windows,
SysUtils;
const
FStrWhenDone: array[0..1] of string = (' /C', ' /K');
FStrAutoRun: array[0..1] of string = ('', ' /D');
FStrOutType: array[0..1] of string = (' /A', ' /U');
FStrColors: array[0..16] of string = ('', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
FStrUseExt: array[0..2] of string = ('', ' /E:ON', ' /E:OFF');
constructor TSysCommand.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOutputType := cotANSI;
FAutoRunCmds := carDefault;
FCmdExtensions := cexDefault;
FWhenDone := cwdClose;
FBkColor := cclNone;
FFgColor := cclNone;
WindowTitle := '';
FCmdsList := TStringList.Create;
end;
destructor TSysCommand.Destroy;
begin
inherited Destroy;
FCmdsList.Destroy;
end;
function TSysCommand.GetParamsString: string;
// Returns a string containing the parameters to be passed to 'COMSPEC'
begin
Result := '';
Result := Result + FStrOutType[Ord(FOutputType)];
Result := Result + FStrAutoRun[Ord(FAutoRunCmds)];
Result := Result + FStrUseExt[Ord(FCmdExtensions)];
Result := Result + FStrWhenDone[Ord(FWhenDone)];
end;
procedure TSysCommand.GetInternalCmdsList(var AList: TStringList);
begin
// Clean string list
AList.Clear;
// Insert all commands
if FWindowTitle <> '' then
AList.Add('TITLE ' + FWindowTitle);
if (FBkColor <> cclNone) and (FFgColor <> cclNone) then
AList.Add('COLOR ' + FStrColors[Ord(FBkColor)] + FStrColors[Ord(FFgColor)]);
end;
function TSysCommand.GetCommandsString: string;
// Return a string with internal commands and user commands
var
FList: TStringList;
idx: Integer;
s: string;
begin
s := '';
// Get internal command list as string
FList := TStringList.Create;
GetInternalCmdsList(FList);
for idx := 0 to FList.Count - 1 do
s := s + FList.Strings[idx] + ' && ';
// Concat with user commands list
for idx := 0 to FCmdsList.Count - 1 do
s := s + FCmdsList.Strings[idx] + ' && ';
// Delete last &&
Delete(s, Length(s) - 3, 4);
// Return commands string
Result := '"' + s + '"';
end;
function TSysCommand.Execute: Boolean;
var
FCmd: string;
FExec: string;
begin
// get name and path of command processor
FCmd := GetEnvironmentVariable('COMSPEC');
FExec := FCmd + ' ' + GetParamsString + ' ' + GetCommandsString;
Result := WinExec(PChar(FExec), SW_SHOWNORMAL) > 31;
end;
end.
Note: The TSysCommand probably can be extended to support Linux Terminal Mode.
It would be a fine addition and a good reason to use this component in a application.
2006. október 4., szerda
How to search a TRichEdit for lines with a special pattern and change their colour
Problem/Question/Abstract:
How do I scan a TRichEdit from top to bottom and check for lines with a special pattern to change color? I only know SelStart and SelLength, but how do I select a line at a time?
Answer:
var
S: string;
i: Integer;
{ ... }
with richedit1 do
begin
lines.beginupdate;
try
for i := 0 to lines.count - 1 do
begin
S := Lines[i];
if LineShouldBeColored(S) then
begin
SelStart := Perform(EM_LINEINDEX, i, 0);
SelLength := Length(S);
SelAttributes.Color := clRed;
end;
end;
finally
SelStart := 0;
Perform(EM_SCROLLCARET, 0, 0);
lines.endupdate;
end;
end;
2006. október 3., kedd
How to refresh the client rectangle
Problem/Question/Abstract:
A config form allows the user to change the background, but I can't refresh the complete client area when coming back from the config form. Only the config form area is refreshed.
Answer:
procedure TMainWin.InvalidateClient;
var
R: TRect;
begin
R := Classes.Rect(0, 0, ClientWidth, ClientHeight);
InvalidateRect(ClientHandle, @R, true);
end;
2006. október 2., hétfő
How to save several TBitmaps into one file
Problem/Question/Abstract:
Does anybody know whether it is possible to write some small TBitmaps with different widths and heights into one file?
Answer:
Saving the TBitmap to a Stream, and appending other TBitmaps to that stream, then saving the stream to disk would be the method.
procedure SaveBitmapToStream(aBitmap: TBitmap; aStream: TStream);
var
ms: TMemoryStream;
size: Integer;
begin
Assert(Assigned(aBitmap));
Assert(Assigned(aStream));
ms := TMemoryStream.Create;
try
aBitmap.SaveToStream(ms);
ms.position := 0;
size := ms.Size;
aStream.WriteBuffer(size, Sizeof(size));
aStream.CopyFrom(ms, size);
finally
ms.free
end;
end;
then
aStream.SaveToFile('FileName');
to read then first off do:
aStream.LoadFromFile('FileName');
then
procedure LoadBitmapFromStream(aBitmap: TBitmap; aStream: TStream);
var
ms: TMemoryStream;
size: Integer;
begin
Assert(Assigned(aBitmap));
Assert(Assigned(aStream));
ms := TMemoryStream.Create;
try
aStream.ReadBuffer(size, Sizeof(size));
ms.CopyFrom(aStream, size);
ms.position := 0;
aBitmap.LoadfromStream(ms);
finally
ms.free
end;
end;
2006. október 1., vasárnap
How to get the RGB value of a pixel under the mouse cursor
Problem/Question/Abstract:
How can I get the hex RGB value of the pixel under the cursor? I want to be able to do this when the cursor is over an image.
Answer:
Solve 1:
Mouse movement:
procedure TForm1.ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
ColNumb := Image.Canvas.Pixels[X, Y]; {The image can't be a JPG}
GetRGB(ColNumb, R, G, B);
{Here are the RGB values you need}
end;
The GetRGB procedure:
procedure GetRGB(Col: TColor; var R, G, B: Byte);
var
Color: $0..$FFFFFFFF;
begin
Color := ColorToRGB(Col);
R := ($000000FF and Color);
G := ($0000FF00 and Color) shr 8;
B := ($00FF0000 and Color) shr 16;
end;
Solve 2:
var
MyColor: TColor;
begin
MyColor := Image1.Canvas.Pixels[x, y];
Label1.Caption := format('Red: %d; Green: %d; Blue:%d',
[GetRValue(MyColor), GetGValue(MyColor), GetBValue(MyColor)]);
end;
Solve 3:
function DesktopColor(const x, y: integer): TColor;
var
c: TCanvas;
begin
c := TCanvas.create;
c.handle := GetWindowDC(GetDesktopWindow);
result := getpixel(c.handle, x, y);
c.free;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
pos: TPoint;
begin
GetCursorPos(Pos);
Panel1.Color := DesktopColor(pos.x, pos.y);
end;
Feliratkozás:
Bejegyzések (Atom)