2004. április 21., szerda
Embedding files in a program
Problem/Question/Abstract:
Have you ever needed to distribute one or more critical data files with a program? Often only your program needs to access the data file(s) and they don't need to be changed by it. How do we stop users from deleting the files?
Answer:
One answer is to store the data file inside our executable (or in a DLL) as a custom (RCDATA) resource and to link the resource into our application using the {$R} directive.
This article shows how to create a resource file containing a copy of any file. The resource file we're going to create has the following format:
a header that introduces the file
a header for our RCDATA resource
the data itself - an RCDATA resource is simply a sequence of bytes
any padding required so that any following resource begins on a DWORD boundary
It's much simpler to create a resource file that is identified by an ordinal (eg 200) than it is to create one identified by a string (eg 'MY_RESOURCE'), since the resource header records are a fixed size in the first case and are variable in the second case. We will only consider the first case here. We will also just copy one file into the resource - it's simple to extend this to more than one.
Because we're sticking with ordinal IDs the resource header can be defined as:
TResHeader = record
DataSize: DWORD; // size of our data
HeaderSize: DWORD; // size of this record
ResType: DWORD; // lo word = $FFFF => ordinal
ResId: DWORD; // lo word = $FFFF => ordinal
DataVersion: DWORD; // *
MemoryFlags: WORD;
LanguageId: WORD; // *
Version: DWORD; // *
Characteristics: DWORD; // *
end;
We will not be using the fields marked * .
Here's the code that creates the resource file and copies in a given file:
procedure CreateResourceFile(
DataFile, ResFile: string; // file names
ResID: Integer // id of resource
);
var
FS, RS: TFileStream;
FileHeader, ResHeader: TResHeader;
Padding: array[0..SizeOf(DWORD) - 1] of Byte;
begin
{ Open input file and create resource file }
FS := TFileStream.Create(// to read data file
DataFile, fmOpenRead);
RS := TFileStream.Create(// to write res file
ResFile, fmCreate);
{ Create res file header - all zeros except
for HeaderSize, ResType and ResID }
FillChar(FileHeader, SizeOf(FileHeader), #0);
FileHeader.HeaderSize := SizeOf(FileHeader);
FileHeader.ResId := $0000FFFF;
FileHeader.ResType := $0000FFFF;
{ Create data header for RC_DATA file
NOTE: to create more than one resource just
repeat the following process, using a different
resource ID each time }
FillChar(ResHeader, SizeOf(ResHeader), #0);
ResHeader.HeaderSize := SizeOf(ResHeader);
// resource id - FFFF says "not a string!"
ResHeader.ResId := $0000FFFF or (ResId shl 16);
// resource type - RT_RCDATA (from Windows unit)
ResHeader.ResType := $0000FFFF
or (WORD(RT_RCDATA) shl 16);
// data file size is size of file
ResHeader.DataSize := FS.Size;
// set required memory flags
ResHeader.MemoryFlags := $0030;
{ Write the headers to the resource file }
RS.WriteBuffer(FileHeader, sizeof(FileHeader));
RS.WriteBuffer(ResHeader, sizeof(ResHeader));
{ Copy the file into the resource }
RS.CopyFrom(FS, FS.Size);
{ Pad data out to DWORD boundary - any old
rubbish will do!}
if FS.Size mod SizeOf(DWORD) <> 0 then
RS.WriteBuffer(Padding, SizeOf(DWORD) -
FS.Size mod SizeOf(DWORD));
{ Close the files }
FS.Free;
RS.Free;
end;
The above code should be sufficient to illustrate the problem, but it is not very elegant - and the streams should be protected by try .. finally blocks. A better solution is to create a class that encapsulates the code. A further improvement would be to permit either strings or ordinals to be used to identify the resource.
On occasion you may want to write formatted data to the resource file rather than just copy a file - this is easy to do. You need to do five things:
write a placeholder header record for your resource and record its position in the stream
write the formatted data to the file (replace the code that copies the file with code that writes the data)
keep a record of the size of the data you are writing
pad the data out to a DWORD boundary
store the length of data (excluding padding) in your header record, return to the position of the placeholder header and overwrite it.
Of course there's now the problem of getting the file information back out of the executable! This is quite a trivial process and is dealt with in another article.
You can download a worked example that demonstrates what has been described here -- it uses the above code. The .zip file contains a pair of projects. The first a program that embeds a supplied rich text file in a resource file. The second program includes the resource file and displays the rich text in a rich edit component.
2004. április 20., kedd
Exchange items in TListView
Problem/Question/Abstract:
Exchange items in TListView
Answer:
Today I want to describe how you may exchange some items in standard TListView. For example, you have 5 items and want to swap positions for first and third items
Problem that standard TListView component haven't such method and you must realize it yourself.
We remember that the standard way from old Pascal times (for numbers) is:
procedure Swap(X, Y: Integer);
var
s: Integer;
begin
s := X;
X := Y;
Y := X
end;
Something similar we can do with TListItem too. But just to save all strings (caption+sub items) somewhere is not enough because TListItem class have a lot of other information (image indexes, pointer as Data, etc)
So correct way is to use Assign method:
procedure ExchangeItems(lv: TListView; const i, j: Integer);
var
tempLI: TListItem;
begin
lv.Items.BeginUpdate;
try
tempLI := TListItem.Create(lv.Items);
tempLI.Assign(lv.Items.Item[i]);
lv.Items.Item[i].Assign(lv.Items.Item[j]);
lv.Items.Item[j].Assign(tempLI);
tempLI.Free;
finally
lv.Items.EndUpdate
end;
end;
So structure is a same as in our sample for Integer. All what we added are BeginUpdate and EndUpdate (just allow to reduce a flickering)
So if you want to exchange items in any ListView, just call this procedure...
2004. április 19., hétfő
Exploring web services in Delphi
Problem/Question/Abstract:
How to write a Web Services Server in Delphi?
Answer:
This article is a continuation of my previous article "Accessing web services using SOAP". In that article, we have seen how can we write a Web Services Client in Delphi using a WSDL file and now we are going to see how can we write a Web Services Server itself in Delphi 6.
Why Web Services?
Web services are basically designed to allow loose coupling between client and server and also they dont require clients to use a specific platform or language. i.e. it's language neutral. Mainly for these reasons among others, these services are becoming more popular and no doubt, they are going to dominate the industry in future.
How Delphi is implementing these services?
Web services server developed in Delphi are using Invokable interfaces. These are interfaces that contain Run Time Type Information(RTTI) and this information will help interpreting calls from clients. There is a separate class defined in Delphi called IInvokable and whenever we write a web services server in Delphi, it should use this class. This class is basically derived from IInterface class.
Whenever a client uses a service by calling one of its methods, that method has to be identified and a proper response has to be given to the client. Right? For that purpose, there are two more components in addition to Invokable interfaces.
1. Dispatcher
Whenever a client requests a service by calling a specific method in the server, that request has been passed on to the Invoker. No need to say, the request will always be a SOAP message. This dispatcher is implemented in Delphi using a separate class called THTTPSoapDispather.
2. Invoker
Once it receives the SOAP message from the Dispatcher, it finds the relevant interface and executes the call and send a response as another SOAP message. This Invoker is implemented using another class called THTTPSoapPascalInvoker.
And one more thing, as of now these two classes are designed to support only HTTP request and response.
In total, all we need is nothing but interfaces and classes that implement those interfaces. That's all. Once you desinged both, you need to register them. After that, all the request/response will be handled by both the Dispatcher and Invoker. Pretty simple? huh?
Now let us try writing a simple Web Services Server in Delphi 6. I'm not going to give fully functionaly example of a web service server rather i'm just going to discuss what are all the steps in developing a Web services server in Delphi with some sample units.
The following is a sample Interface unit :
unit uConversionIntf;
interface
type
ITConversion = interface(IInvokable)
['{878DD241-526E-48CD-90B4-2749471D2DE5}']
//A sample function to convert Celcius to Farenheit
function CelciusToFahrenheit(Celcius: Real): Real; stdcall;
{Here you can define your services}
end;
implementation
uses
InvokeRegistry; // Unit contains methods on how to register the interface
initialization
InvRegistry.RegisterInterface(TypeInfo(ITConversion));
end.
The unit above is a sample having some sample methods that define the web services. Here I added a function to convert Celcius to Farenheit. Like that you can define as many functions as possible. And the "['{878DD241-526E-48CD-90B4-2749471D2DE5}']" is nothing but the GUID for that interface ITConversion. This you can generate in the Delphi IDE by pressing Ctrl+Shift+G, the easiest way of creating GUID in Delphi.
The unit InvokeRegistry contains methods needed to register the interface with your system. We need to register that interface in the initialization section. That's all about defining the interface.
Then the next step is to implement the interface in a class. For that we need to create another unit with the implementation class.
Here is the sample implementation class:
unit ConversionImpl;
interface
uses
InvokeRegistry;
type
TConversionService = class(TInvokableClass, ITConversion)
public
function CelciusToFahrenheit(Celcius: Real): Real; stdcall;
end;
implementation
function CelciusToFahrenheit(Celcius: Real): Real; stdcall;
begin
//Here you can write the code to convert the celcius to farenheit.
end;
initialization
InvRegistry.RegisterInvokableClass(TConversionService);
end.
Here also you can see in the initialization section that you need to register the implementation class with the invokation registry. Now we have two units, one defining the interface and the other implementing that interface in a class.
As of now, we need to create these two units by hand and add code to register both the interfaces and implementation classes; It would be nice if we have a wizard of some kind to create these two units automatically. I dont see any such wizard right now in Delphi 6 Trial Edition downloaded version. And I heard that there is a wizard available in Delphi 6 to generate these two files. If not, I'm thinking of writing such a wizard. Please keep me informed if you know anything further on this.
Next step is to create a SOAP application in Delphi and include these two units into that application. Once you are done that, the Web services server in Delphi in ready to use.
How to create a SOAP server application?
In the Delphi IDE, select New | Other | Web Services and select SOAP Server Application.
Then there will be a dialog showing you the types of web servers.
You can choose the type you want; for our example purpose, letz choose ISAPI/NSAPI Dynamic Link Library
This will create a web module with three components, out of that we discussed two of 'em already and the new component is the TWSDLHTMLPublish. (Let us see about this later in this article)
The sample source of the web module would look like this:
unit uConversion;
interface
uses
SysUtils, Classes, HTTPApp;
type
TWebModule1 = class(TWebModule)
HTTPSoapDispatcher1: THTTPSoapDispatcher;
HTTPSoapPascalInvoker1: THTTPSoapPascalInvoker;
WSDLHTMLPublish1: TWSDLHTMLPublish;
private
{ Private declarations }
public
{ Public declarations }
end;
var
WebModule1: TWebModule1;
implementation
{$R *.DFM}
end.
In this unit, you can see both the dispatcher and invoker in addition to the WSDL publisher component.
Now add both the Interface and the implementation units we created before to this newly created project.
Once you added those two unit, build the application and this will result in a DLL;
How can we use this server in Delphi?
This is pretty simple. You just need to add the Interface unit into your normal Delphi application and call the functions implemented in the server.
How can we use this server in applications other than Delphi?
Here comes the WSDL file. You just need to generate the WSDL with the server you have written. How can we do that? Now comes the WSDLHTMLPublish component. This component will help you generate that WSDL file.
What you need to generate/publish that WSDL file?
You need a web server, atleast a Personal Web Server and should be running.
You just need to put that DLL in the C:\Inetpub\Scripts directory and browse that DLL through a web server. i.e. http://localhost/scripts/
So when you browse through a web server, you will be getting the WSDL file. Also if you set the AdminEnabled property of the WSDLHTMLPublish component to true, you would be able to see the administrator previleges with a click of an additional button on the browser.
This is a simple type of web server without any much complexities. The example I have explained involved only simple data types like Real, String etc., but actually you can write a server that return complex types like returning an object etc., But this would be the basic that you need to understand before writing such complex ones.
P.S.: One of our members reported me of a problem viewing the WSDL file while browsing the dll through a web server. Actually I forgot to mention one thing about that. We need to specify WSDL after the dll name while browing through a web server. i.e. http://localhost/scripts/ConversionService.dll/WSDL.
And the other problem is unloading the DLL from memory after first use. The solution for this is to stop the web server and try building the dll again. It should normally work. Because when you use for the first time through a web server, that web server will hold a reference to that dll; so if you stop the web server that reference should be freed. This is been a problem with PWS and IIS; sometimes works sometimes not!! In that case, we may need to restart the entire machine itself(which is not a solution for this) ; I have been experiencing such problems often; so if anyone has any experience on this, please keep our members posted.
2004. április 18., vasárnap
OpenGL III: Moving and rotating 3D shapes
Problem/Question/Abstract:
In this article I'll show you how to create 3D shapes, which is just an extension of the last article, also you'll see how to rotate around the same shape axis or rotate around other object (like the solar system)
Answer:
Ok, this is the 3rd of a series of articles on OpenGL, so far we have seen:
OpenGL I: Hello World, Setup a Delphi OpenGL Application
OpenGL II: Moving and rotating 2D shapes
Now we're gonna expand on the last article to create 3D shapes, rotate them around their own axis and rotating objects around some other object (like a solar system)
To accomplish such thing we're still going to use the same basic OpenGL instructions but because this is graphics, one line in the wrong place makes a huge difference As I stated in my last article, OpenGL just follows instructions like "move forward", "turn left X degrees", etc, so just with that you know is not the same:
"move forward 10 units", "turn left 90 degrees"
than:
"turn left 90 degrees", "move forward 10 units"
simple, right??
well, just those simple rules will make a difference when you want to rotate an object around it's own axis or around other object axis
Rotating in the object own axis would be something like:
"move to 0, 0, 0", "move forward 10 units", "turn left X degrees", "draw a shape", "inc(X, 1.0)"
very simple, we move to a fixed position (10 units forward) turn X degrees, X gets incremented later, so that makes the shape rotate around its own axis and then we draw the shape, and increment the angle
In Delphi would be something like:
glTranslatef(-0.5, 0.0, -15.0); // Move 0.5 Units Left And 15.0 units Into The Screen
glRotatef(rquad, 0.0, 1.0, 1.0); // Rotate The Quad On The Y and Z axis ( NEW )
glBegin(GL_QUADS); // We are going to draw a cube, so let's use QUADS
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.5, 0.5, -0.5); // Top Left
glVertex3f(-0.5, 0.5, -0.5); // Top Right
{.
.
.}
glEnd();
rquad := rquad + 1.0;
Now to rotate around that object we just drew, we would have to do the following:
"cancel previous rotation", "turn left X degrees", "move 3 units into screen", "turn right Y degrees", "draw shape"
The first important thing to notice here is that we didn't use "move 0, 0, 0", which means we're going to keep drawing from the position where we drew the last shape
The second thing is cancelling the previous rotation, why is that? Because if you don't, when you move forward X units, is going to move into whatever direction the last angle was, that might be what you want, but if you want your shape to rotate in a different axis, then you have to cancel the rotation, and then rotate to where you want and then move... confusing? luckily you'll get to play with the source code and see what happens when you cancel and when you don't.
The third thing is rotating to the angle that you want (this actually makes the rotation around the first object posible)
Move 3 units into screen, This to separate the new shape from the last, if we don't move to any direction, we will draw this shape in the same place!, maybe rotated to a different angle but in the same coordinates
Finally we do a last rotation around a new variable angle and draw the shape. This last rotation will make the new object rotate around it's own axis just like the solar system, the earth rotates around the sun, and then also rotates around it's own axis, makes sense? I hope so
let's look at the Delphi code:
//Notice we don't use glLoadIdentity here, which means we are at whatever position we drew the quad
glRotatef(-rquad, 0.0, 1.0, 1.0); // Cancel the previous rotation!!!
glRotatef(rtri, 0.0, 1.0, 0.0); // Rotate The Triangle On The Y axis (around the quad)
glTranslatef(0.0, 0.0, 3.0); // Move 3.0 Units Into The screen
glRotatef(rtri, 0.0, 0.0, 1.0);
// Let's rotate the pyramid, while we rotate around the quad
glBegin(GL_TRIANGLES); // We're gonna draw a pyramid, so let's use TRIANGLES
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Front)
{.
.
.}
glEnd();
rtri := rtri + 2.0;
ok, that's it on explanations, here's the source code for the drawing procedure I added a polygon to the scene just to show you how to create them Also check the coloring mix on the pyramid
function DrawGLScene(): Bool; { All Rendering Done Here }
begin
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); //Clear Screen and Depth Buffer
glLoadIdentity(); //Reset The View
glTranslatef(-0.5, 0.0, -15.0); // Move 0.5 Units Left And 15.0 units Into The Screen
glRotatef(rquad, 0.0, 1.0, 1.0); // Rotate The Quad On The Y and Z axis ( NEW )
glBegin(GL_QUADS); // We are going to draw a cube, so let's use QUADS
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.5, 0.5, -0.5); // Top Left
glVertex3f(-0.5, 0.5, -0.5); // Top Right
glVertex3f(-0.5, 0.5, 0.5); // Bottom Right
glVertex3f(0.5, 0.5, 0.5); // Bottom Left
glColor3f(1.0, 0.5, 0.0);
glVertex3f(0.5, -0.5, -0.5); // Top Left
glVertex3f(-0.5, -0.5, -0.5); // Top Right
glVertex3f(-0.5, -0.5, 0.5); // Bottom Right
glVertex3f(0.5, -0.5, 0.5); // Bottom Left
glColor3f(1.0, 0.0, 0.0);
glVertex3f(0.5, 0.5, 0.5); // Top Left
glVertex3f(-0.5, 0.5, 0.5); // Top Right
glVertex3f(-0.5, -0.5, 0.5); // Bottom Right
glVertex3f(0.5, -0.5, 0.5); // Bottom Left
glColor3f(1.0, 1.0, 0.0);
glVertex3f(0.5, -0.5, -0.5); // Top Left
glVertex3f(-0.5, -0.5, -0.5); // Top Right
glVertex3f(-0.5, 0.5, -0.5); // Bottom Right
glVertex3f(0.5, 0.5, -0.5); // Bottom Left
glColor3f(0.0, 0.0, 1.0);
glVertex3f(-0.5, 0.5, 0.5); // Top Left
glVertex3f(-0.5, 0.5, -0.5); // Top Right
glVertex3f(-0.5, -0.5, -0.5); // Bottom Right
glVertex3f(-0.5, -0.5, 0.5); // Bottom Left
glColor3f(1.0, 0.0, 1.0);
glVertex3f(0.5, 0.5, -0.5); // Top Left
glVertex3f(0.5, 0.5, 0.5); // Top Right
glVertex3f(0.5, -0.5, 0.5); // Bottom Right
glVertex3f(0.5, -0.5, -0.5); // Bottom Left
glEnd();
//Notice we don't use glLoadIdentity here, which means we are at whatever position we drew the quad
glRotatef(-rquad, 0.0, 1.0, 1.0); // Cancel the previous rotation!!!
glRotatef(rtri, 0.0, 1.0, 0.0);
// Rotate The Triangle On The Y axis (around the quad)
glTranslatef(0.0, 0.0, 3.0); // Move 3.0 Units Into The screen
glRotatef(rtri, 0.0, 0.0, 1.0);
// Let's rotate the pyramid, while we rotate around the quad
glBegin(GL_TRIANGLES); // We're gonna draw a pyramid, so let's use TRIANGLES
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Front)
glColor3f(0.0, 1.0, 0.0); // Green
glVertex3f(-0.5, -0.5, 0.5); // Left Of Triangle (Front)
glColor3f(0.0, 0.0, 1.0); // Blue
glVertex3f(0.5, -0.5, 0.5); // Right Of Triangle (Front)
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Right)
glColor3f(0.0, 0.0, 1.0); // Blue
glVertex3f(0.5, -0.5, 0.5); // Left Of Triangle (Right)
glColor3f(0.0, 1.0, 0.0); // Green
glVertex3f(0.5, -0.5, -0.5); // Right Of Triangle (Right)
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Back)
glColor3f(0.0, 1.0, 0.0); // Green
glVertex3f(0.5, -0.5, -0.5); // Left Of Triangle (Back)
glColor3f(0.0, 0.0, 1.0); // Blue
glVertex3f(-0.5, -0.5, -0.5); // Right Of Triangle (Back)
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Left)
glColor3f(0.0, 0.0, 1.0); // Blue
glVertex3f(-0.5, -0.5, -0.5); // Left Of Triangle (Left)
glColor3f(0.0, 1.0, 0.0); // Green
glVertex3f(-0.5, -0.5, 0.5); // Right Of Triangle (Left)
glEnd();
glLoadIdentity(); // Move to (0, 0, 0)
glTranslatef(1.5, 0.0, -6.0); // Move 1.5 Right and -6.0 intro screen
glRotatef(rpol, 0.0, 0.0, 1.0); // rotate on Z axis
glColor3f(0.0, 0.0, 1.0); // Add some color
glBegin(GL_POLYGON); // Draw A Polygon (I can put many points in here)
glVertex3f(-0.5, 0.5, 0.0); // Top Left
glVertex3f(0.0, 0.75, 0.0); // Upper point
glVertex3f(0.5, 0.5, 0.0); // Top Right
glVertex3f(0.5, -0.5, 0.0); // Bottom Right
glVertex3f(0.0, -0.75, 0.0); // Lower point
glVertex3f(-0.5, -0.5, 0.0); // Bottom Left
glEnd();
rtri := rtri + 2.0;
rquad := rquad + 1.0;
rpol := rpol + 1.0;
Result := True
end;
That's it, I hope it wasn't too confusing, play with the code, see what happens when you comment this or that line.
In this article I'll show you how to create 3D shapes, which is just an extension of the last article, also you'll see how to rotate around the same shape axis or rotate around other object (like the solar system)
Answer:
Ok, this is the 3rd of a series of articles on OpenGL, so far we have seen:
OpenGL I: Hello World, Setup a Delphi OpenGL Application
OpenGL II: Moving and rotating 2D shapes
Now we're gonna expand on the last article to create 3D shapes, rotate them around their own axis and rotating objects around some other object (like a solar system)
To accomplish such thing we're still going to use the same basic OpenGL instructions but because this is graphics, one line in the wrong place makes a huge difference As I stated in my last article, OpenGL just follows instructions like "move forward", "turn left X degrees", etc, so just with that you know is not the same:
"move forward 10 units", "turn left 90 degrees"
than:
"turn left 90 degrees", "move forward 10 units"
simple, right??
well, just those simple rules will make a difference when you want to rotate an object around it's own axis or around other object axis
Rotating in the object own axis would be something like:
"move to 0, 0, 0", "move forward 10 units", "turn left X degrees", "draw a shape", "inc(X, 1.0)"
very simple, we move to a fixed position (10 units forward) turn X degrees, X gets incremented later, so that makes the shape rotate around its own axis and then we draw the shape, and increment the angle
In Delphi would be something like:
glTranslatef(-0.5, 0.0, -15.0); // Move 0.5 Units Left And 15.0 units Into The Screen
glRotatef(rquad, 0.0, 1.0, 1.0); // Rotate The Quad On The Y and Z axis ( NEW )
glBegin(GL_QUADS); // We are going to draw a cube, so let's use QUADS
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.5, 0.5, -0.5); // Top Left
glVertex3f(-0.5, 0.5, -0.5); // Top Right
{.
.
.}
glEnd();
rquad := rquad + 1.0;
Now to rotate around that object we just drew, we would have to do the following:
"cancel previous rotation", "turn left X degrees", "move 3 units into screen", "turn right Y degrees", "draw shape"
The first important thing to notice here is that we didn't use "move 0, 0, 0", which means we're going to keep drawing from the position where we drew the last shape
The second thing is cancelling the previous rotation, why is that? Because if you don't, when you move forward X units, is going to move into whatever direction the last angle was, that might be what you want, but if you want your shape to rotate in a different axis, then you have to cancel the rotation, and then rotate to where you want and then move... confusing? luckily you'll get to play with the source code and see what happens when you cancel and when you don't.
The third thing is rotating to the angle that you want (this actually makes the rotation around the first object posible)
Move 3 units into screen, This to separate the new shape from the last, if we don't move to any direction, we will draw this shape in the same place!, maybe rotated to a different angle but in the same coordinates
Finally we do a last rotation around a new variable angle and draw the shape. This last rotation will make the new object rotate around it's own axis just like the solar system, the earth rotates around the sun, and then also rotates around it's own axis, makes sense? I hope so
let's look at the Delphi code:
//Notice we don't use glLoadIdentity here, which means we are at whatever position we drew the quad
glRotatef(-rquad, 0.0, 1.0, 1.0); // Cancel the previous rotation!!!
glRotatef(rtri, 0.0, 1.0, 0.0); // Rotate The Triangle On The Y axis (around the quad)
glTranslatef(0.0, 0.0, 3.0); // Move 3.0 Units Into The screen
glRotatef(rtri, 0.0, 0.0, 1.0);
// Let's rotate the pyramid, while we rotate around the quad
glBegin(GL_TRIANGLES); // We're gonna draw a pyramid, so let's use TRIANGLES
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Front)
{.
.
.}
glEnd();
rtri := rtri + 2.0;
ok, that's it on explanations, here's the source code for the drawing procedure I added a polygon to the scene just to show you how to create them Also check the coloring mix on the pyramid
function DrawGLScene(): Bool; { All Rendering Done Here }
begin
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); //Clear Screen and Depth Buffer
glLoadIdentity(); //Reset The View
glTranslatef(-0.5, 0.0, -15.0); // Move 0.5 Units Left And 15.0 units Into The Screen
glRotatef(rquad, 0.0, 1.0, 1.0); // Rotate The Quad On The Y and Z axis ( NEW )
glBegin(GL_QUADS); // We are going to draw a cube, so let's use QUADS
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.5, 0.5, -0.5); // Top Left
glVertex3f(-0.5, 0.5, -0.5); // Top Right
glVertex3f(-0.5, 0.5, 0.5); // Bottom Right
glVertex3f(0.5, 0.5, 0.5); // Bottom Left
glColor3f(1.0, 0.5, 0.0);
glVertex3f(0.5, -0.5, -0.5); // Top Left
glVertex3f(-0.5, -0.5, -0.5); // Top Right
glVertex3f(-0.5, -0.5, 0.5); // Bottom Right
glVertex3f(0.5, -0.5, 0.5); // Bottom Left
glColor3f(1.0, 0.0, 0.0);
glVertex3f(0.5, 0.5, 0.5); // Top Left
glVertex3f(-0.5, 0.5, 0.5); // Top Right
glVertex3f(-0.5, -0.5, 0.5); // Bottom Right
glVertex3f(0.5, -0.5, 0.5); // Bottom Left
glColor3f(1.0, 1.0, 0.0);
glVertex3f(0.5, -0.5, -0.5); // Top Left
glVertex3f(-0.5, -0.5, -0.5); // Top Right
glVertex3f(-0.5, 0.5, -0.5); // Bottom Right
glVertex3f(0.5, 0.5, -0.5); // Bottom Left
glColor3f(0.0, 0.0, 1.0);
glVertex3f(-0.5, 0.5, 0.5); // Top Left
glVertex3f(-0.5, 0.5, -0.5); // Top Right
glVertex3f(-0.5, -0.5, -0.5); // Bottom Right
glVertex3f(-0.5, -0.5, 0.5); // Bottom Left
glColor3f(1.0, 0.0, 1.0);
glVertex3f(0.5, 0.5, -0.5); // Top Left
glVertex3f(0.5, 0.5, 0.5); // Top Right
glVertex3f(0.5, -0.5, 0.5); // Bottom Right
glVertex3f(0.5, -0.5, -0.5); // Bottom Left
glEnd();
//Notice we don't use glLoadIdentity here, which means we are at whatever position we drew the quad
glRotatef(-rquad, 0.0, 1.0, 1.0); // Cancel the previous rotation!!!
glRotatef(rtri, 0.0, 1.0, 0.0);
// Rotate The Triangle On The Y axis (around the quad)
glTranslatef(0.0, 0.0, 3.0); // Move 3.0 Units Into The screen
glRotatef(rtri, 0.0, 0.0, 1.0);
// Let's rotate the pyramid, while we rotate around the quad
glBegin(GL_TRIANGLES); // We're gonna draw a pyramid, so let's use TRIANGLES
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Front)
glColor3f(0.0, 1.0, 0.0); // Green
glVertex3f(-0.5, -0.5, 0.5); // Left Of Triangle (Front)
glColor3f(0.0, 0.0, 1.0); // Blue
glVertex3f(0.5, -0.5, 0.5); // Right Of Triangle (Front)
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Right)
glColor3f(0.0, 0.0, 1.0); // Blue
glVertex3f(0.5, -0.5, 0.5); // Left Of Triangle (Right)
glColor3f(0.0, 1.0, 0.0); // Green
glVertex3f(0.5, -0.5, -0.5); // Right Of Triangle (Right)
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Back)
glColor3f(0.0, 1.0, 0.0); // Green
glVertex3f(0.5, -0.5, -0.5); // Left Of Triangle (Back)
glColor3f(0.0, 0.0, 1.0); // Blue
glVertex3f(-0.5, -0.5, -0.5); // Right Of Triangle (Back)
glColor3f(1.0, 0.0, 0.0); // Red
glVertex3f(0.0, 0.5, 0.0); // Top Of Triangle (Left)
glColor3f(0.0, 0.0, 1.0); // Blue
glVertex3f(-0.5, -0.5, -0.5); // Left Of Triangle (Left)
glColor3f(0.0, 1.0, 0.0); // Green
glVertex3f(-0.5, -0.5, 0.5); // Right Of Triangle (Left)
glEnd();
glLoadIdentity(); // Move to (0, 0, 0)
glTranslatef(1.5, 0.0, -6.0); // Move 1.5 Right and -6.0 intro screen
glRotatef(rpol, 0.0, 0.0, 1.0); // rotate on Z axis
glColor3f(0.0, 0.0, 1.0); // Add some color
glBegin(GL_POLYGON); // Draw A Polygon (I can put many points in here)
glVertex3f(-0.5, 0.5, 0.0); // Top Left
glVertex3f(0.0, 0.75, 0.0); // Upper point
glVertex3f(0.5, 0.5, 0.0); // Top Right
glVertex3f(0.5, -0.5, 0.0); // Bottom Right
glVertex3f(0.0, -0.75, 0.0); // Lower point
glVertex3f(-0.5, -0.5, 0.0); // Bottom Left
glEnd();
rtri := rtri + 2.0;
rquad := rquad + 1.0;
rpol := rpol + 1.0;
Result := True
end;
That's it, I hope it wasn't too confusing, play with the code, see what happens when you comment this or that line.
2004. április 17., szombat
Convert HTML to RTF
Problem/Question/Abstract:
How to convert HTML to RTF?
Answer:
{ HTML to RTF by Falk Schulze }
procedure HTMLtoRTF(html: string; var rtf: TRichedit);
var
i, dummy, row: Integer;
cfont: TFont; { Standard sschrift }
Tag, tagparams: string;
params: TStringList;
function GetTag(s: string; var i: Integer; var Tag, tagparams: string): Boolean;
var
a_tag: Boolean;
begin
GetTag := False;
Tag := '';
tagparams := '';
a_tag := False;
while i <= Length(s) do
begin
Inc(i);
// es wird nochein tag ge�ffnet --> das erste war kein tag;
if s[i] = '<' then
begin
GetTag := False;
Exit;
end;
if s[i] = '>' then
begin
GetTag := True;
Exit;
end;
if not a_tag then
begin
if s[i] = ' ' then
begin
if Tag <> '' then
a_tag := True;
end
else
Tag := Tag + s[i];
end
else
tagparams := tagparams + s[i];
end;
end;
procedure GetTagParams(tagparams: string; var params: TStringList);
var
i: Integer;
s: string;
gleich: Boolean;
// kontrolliert ob nach dem zeichen bis zum n�chsten zeichen ausser
// leerzeichen ein Ist-Gleich-Zeichen kommt
function notGleich(s: string; i: Integer): Boolean;
begin
notGleich := True;
while i <= Length(s) do
begin
Inc(i);
if s[i] = '=' then
begin
notGleich := False;
Exit;
end
else if s[i] <> ' ' then
Exit;
end;
end;
begin
Params.Clear;
s := '';
for i := 1 to Length(tagparams) do
begin
if (tagparams[i] <> ' ') then
begin
if tagparams[i] <> '=' then
gleich := False;
if (tagparams[i] <> '''') and (tagparams[i] <> '"') then
s := s + tagparams[i]
end
else
begin
if (notGleich(tagparams, i)) and (not Gleich) then
begin
params.Add(s);
s := '';
end
else
Gleich := True;
end;
end;
params.Add(s);
end;
function HtmlToColor(Color: string): TColor;
begin
Result := StringToColor('$' + Copy(Color, 6, 2) + Copy(Color, 4,
2) + Copy(Color, 2, 2));
end;
procedure TransformSpecialChars(var s: string; i: Integer);
var
c: string;
z, z2: Byte;
i2: Integer;
const
nchars = 9;
chars: array[1..nchars, 1..2] of string =
(('�', '�'), ('�', '�'), ('�', '�'), ('�', '�'),
('�', '�'), ('�', '�'), ('�', '�'), ('<', '<'),
('>', '>'));
begin
// Maximal die n�chsten 7 zeichen auf sonderzeichen �berpr�fen
c := '';
i2 := i;
for z := 1 to 7 do
begin
c := c + s[i2];
for z2 := 1 to nchars do
begin
if chars[z2, 1] = c then
begin
Delete(s, i, Length(c));
Insert(chars[z2, 2], s, i);
Exit;
end;
end;
Inc(i2);
end;
end;
// HtmlTag Schriftgr��e in pdf gr��e umwandeln
function CalculateRTFSize(pt: Integer): Integer;
begin
case pt of
1: Result := 6;
2: Result := 9;
3: Result := 12;
4: Result := 15;
5: Result := 18;
6: Result := 22;
else
Result := 30;
end;
end;
// Die Font-Stack Funktionen
type
fontstack = record
Font: array[1..100] of tfont;
Pos: Byte;
end;
procedure CreateFontStack(var s: fontstack);
begin
s.Pos := 0;
end;
procedure PushFontStack(var s: Fontstack; fnt: TFont);
begin
Inc(s.Pos);
s.Font[s.Pos] := TFont.Create;
s.Font[s.Pos].Assign(fnt);
end;
procedure PopFontStack(var s: Fontstack; var fnt: TFont);
begin
if (s.Font[s.Pos] <> nil) and (s.Pos > 0) then
begin
fnt.Assign(s.Font[s.Pos]);
// vom stack nehmen
s.Font[s.Pos].Free;
Dec(s.Pos);
end;
end;
procedure FreeFontStack(var s: Fontstack);
begin
while s.Pos > 0 do
begin
s.Font[s.Pos].Free;
Dec(s.Pos);
end;
end;
var
fo_cnt: array[1..1000] of tfont;
fo_liste: array[1..1000] of Boolean;
fo_pos: TStringList;
fo_stk: FontStack;
wordwrap, liste: Boolean;
begin
CreateFontStack(fo_Stk);
fo_Pos := TStringList.Create;
rtf.Lines.BeginUpdate;
rtf.Lines.Clear;
// Das wordwrap vom richedit merken
wordwrap := rtf.wordwrap;
rtf.WordWrap := False;
// erste Zeile hinzuf�gen
rtf.Lines.Add('');
Params := TStringList.Create;
cfont := TFont.Create;
cfont.Assign(rtf.Font);
i := 1;
row := 0;
Liste := False;
// Den eigentlichen Text holen und die Formatiorung merken
rtf.selstart := 0;
if Length(html) = 0 then
Exit;
repeat;
if html[i] = '<' then
begin
dummy := i;
GetTag(html, i, Tag, tagparams);
GetTagParams(tagparams, params);
// Das Font-Tag
if Uppercase(Tag) = 'FONT' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
if params.Values['size'] <> '' then
cfont.Size := CalculateRTFSize(StrToInt(params.Values['size']));
if params.Values['color'] <> '' then
cfont.Color :=
htmltocolor(params.Values['color']);
end
else if Uppercase(Tag) = '/FONT' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H1' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 6;
end
else if Uppercase(Tag) = '/H1' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H2' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 9;
end
else if Uppercase(Tag) = '/H2' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H3' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 12;
end
else if Uppercase(Tag) = '/H3' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H4' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 15;
end
else if Uppercase(Tag) = '/H4' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H5' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 18;
end
else if Uppercase(Tag) = '/H5' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H6' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 22;
end
else if Uppercase(Tag) = '/H6' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H7' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 27;
end
else if Uppercase(Tag) = '/H7' then
popFontstack(fo_stk, cfont)
else // Bold-Tag
if Uppercase(Tag) = 'B' then
cfont.Style := cfont.Style + [fsbold]
else if Uppercase(Tag) = '/B' then
cfont.Style := cfont.Style - [fsbold]
else // Italic-Tag
if Uppercase(Tag) = 'I' then
cfont.Style := cfont.Style + [fsitalic]
else if Uppercase(Tag) = '/I' then
cfont.Style := cfont.Style - [fsitalic]
else // underline-Tag
if Uppercase(Tag) = 'U' then
cfont.Style := cfont.Style + [fsunderline]
else if Uppercase(Tag) = '/U' then
cfont.Style := cfont.Style - [fsunderline]
else // underline-Tag
if Uppercase(Tag) = 'UL' then
liste := True
else if Uppercase(Tag) = '/UL' then
begin
liste := False;
rtf.Lines.Add('');
Inc(row);
rtf.Lines.Add('');
Inc(row);
end
else // BR - Breakrow tag
if (Uppercase(Tag) = 'BR') or (Uppercase(Tag) = 'LI')
then
begin
rtf.Lines.Add('');
Inc(row);
end;
// unbekanntes tag als text ausgeben
// else rtf.Lines[row]:=RTF.lines[row]+'<'+tag+' '+tagparams+'>';
fo_pos.Add(IntToStr(rtf.selstart));
fo_cnt[fo_pos.Count] := TFont.Create;
fo_cnt[fo_pos.Count].Assign(cfont);
fo_liste[fo_pos.Count] := liste;
end
else
begin
// Spezialzeichen �bersetzen
if html[i] = '&' then
Transformspecialchars(html, i);
if (Ord(html[i]) <> 13) and (Ord(html[i]) <> 10) then
rtf.Lines[row] := RTF.Lines[row] + html[i];
end;
Inc(i);
until i >= Length(html);
// dummy eintragen
fo_pos.Add('999999');
// Den fertigen Text formatieren
for i := 0 to fo_pos.Count - 2 do
begin
rtf.SelStart := StrToInt(fo_pos[i]);
rtf.SelLength := StrToInt(fo_pos[i + 1]) - rtf.SelStart;
rtf.SelAttributes.Style := fo_cnt[i + 1].Style;
rtf.SelAttributes.Size := fo_cnt[i + 1].Size;
rtf.SelAttributes.Color := fo_cnt[i + 1].Color;
// die font wieder freigeben;
fo_cnt[i + 1].Free;
end;
// die Paragraphen also Listen setzen
i := 0;
while i <= fo_pos.Count - 2 do
begin
if fo_liste[i + 1] then
begin
rtf.SelStart := StrToInt(fo_pos[i + 1]);
while fo_liste[i + 1] do
Inc(i);
rtf.SelLength := StrToInt(fo_pos[i - 1]) - rtf.SelStart;
rtf.Paragraph.Numbering := nsBullet;
end;
Inc(i);
end;
rtf.Lines.EndUpdate;
Params.Free;
cfont.Free;
rtf.WordWrap := wordwrap;
FreeFontStack(fo_stk);
end;
How to convert HTML to RTF?
Answer:
{ HTML to RTF by Falk Schulze }
procedure HTMLtoRTF(html: string; var rtf: TRichedit);
var
i, dummy, row: Integer;
cfont: TFont; { Standard sschrift }
Tag, tagparams: string;
params: TStringList;
function GetTag(s: string; var i: Integer; var Tag, tagparams: string): Boolean;
var
a_tag: Boolean;
begin
GetTag := False;
Tag := '';
tagparams := '';
a_tag := False;
while i <= Length(s) do
begin
Inc(i);
// es wird nochein tag ge�ffnet --> das erste war kein tag;
if s[i] = '<' then
begin
GetTag := False;
Exit;
end;
if s[i] = '>' then
begin
GetTag := True;
Exit;
end;
if not a_tag then
begin
if s[i] = ' ' then
begin
if Tag <> '' then
a_tag := True;
end
else
Tag := Tag + s[i];
end
else
tagparams := tagparams + s[i];
end;
end;
procedure GetTagParams(tagparams: string; var params: TStringList);
var
i: Integer;
s: string;
gleich: Boolean;
// kontrolliert ob nach dem zeichen bis zum n�chsten zeichen ausser
// leerzeichen ein Ist-Gleich-Zeichen kommt
function notGleich(s: string; i: Integer): Boolean;
begin
notGleich := True;
while i <= Length(s) do
begin
Inc(i);
if s[i] = '=' then
begin
notGleich := False;
Exit;
end
else if s[i] <> ' ' then
Exit;
end;
end;
begin
Params.Clear;
s := '';
for i := 1 to Length(tagparams) do
begin
if (tagparams[i] <> ' ') then
begin
if tagparams[i] <> '=' then
gleich := False;
if (tagparams[i] <> '''') and (tagparams[i] <> '"') then
s := s + tagparams[i]
end
else
begin
if (notGleich(tagparams, i)) and (not Gleich) then
begin
params.Add(s);
s := '';
end
else
Gleich := True;
end;
end;
params.Add(s);
end;
function HtmlToColor(Color: string): TColor;
begin
Result := StringToColor('$' + Copy(Color, 6, 2) + Copy(Color, 4,
2) + Copy(Color, 2, 2));
end;
procedure TransformSpecialChars(var s: string; i: Integer);
var
c: string;
z, z2: Byte;
i2: Integer;
const
nchars = 9;
chars: array[1..nchars, 1..2] of string =
(('�', '�'), ('�', '�'), ('�', '�'), ('�', '�'),
('�', '�'), ('�', '�'), ('�', '�'), ('<', '<'),
('>', '>'));
begin
// Maximal die n�chsten 7 zeichen auf sonderzeichen �berpr�fen
c := '';
i2 := i;
for z := 1 to 7 do
begin
c := c + s[i2];
for z2 := 1 to nchars do
begin
if chars[z2, 1] = c then
begin
Delete(s, i, Length(c));
Insert(chars[z2, 2], s, i);
Exit;
end;
end;
Inc(i2);
end;
end;
// HtmlTag Schriftgr��e in pdf gr��e umwandeln
function CalculateRTFSize(pt: Integer): Integer;
begin
case pt of
1: Result := 6;
2: Result := 9;
3: Result := 12;
4: Result := 15;
5: Result := 18;
6: Result := 22;
else
Result := 30;
end;
end;
// Die Font-Stack Funktionen
type
fontstack = record
Font: array[1..100] of tfont;
Pos: Byte;
end;
procedure CreateFontStack(var s: fontstack);
begin
s.Pos := 0;
end;
procedure PushFontStack(var s: Fontstack; fnt: TFont);
begin
Inc(s.Pos);
s.Font[s.Pos] := TFont.Create;
s.Font[s.Pos].Assign(fnt);
end;
procedure PopFontStack(var s: Fontstack; var fnt: TFont);
begin
if (s.Font[s.Pos] <> nil) and (s.Pos > 0) then
begin
fnt.Assign(s.Font[s.Pos]);
// vom stack nehmen
s.Font[s.Pos].Free;
Dec(s.Pos);
end;
end;
procedure FreeFontStack(var s: Fontstack);
begin
while s.Pos > 0 do
begin
s.Font[s.Pos].Free;
Dec(s.Pos);
end;
end;
var
fo_cnt: array[1..1000] of tfont;
fo_liste: array[1..1000] of Boolean;
fo_pos: TStringList;
fo_stk: FontStack;
wordwrap, liste: Boolean;
begin
CreateFontStack(fo_Stk);
fo_Pos := TStringList.Create;
rtf.Lines.BeginUpdate;
rtf.Lines.Clear;
// Das wordwrap vom richedit merken
wordwrap := rtf.wordwrap;
rtf.WordWrap := False;
// erste Zeile hinzuf�gen
rtf.Lines.Add('');
Params := TStringList.Create;
cfont := TFont.Create;
cfont.Assign(rtf.Font);
i := 1;
row := 0;
Liste := False;
// Den eigentlichen Text holen und die Formatiorung merken
rtf.selstart := 0;
if Length(html) = 0 then
Exit;
repeat;
if html[i] = '<' then
begin
dummy := i;
GetTag(html, i, Tag, tagparams);
GetTagParams(tagparams, params);
// Das Font-Tag
if Uppercase(Tag) = 'FONT' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
if params.Values['size'] <> '' then
cfont.Size := CalculateRTFSize(StrToInt(params.Values['size']));
if params.Values['color'] <> '' then
cfont.Color :=
htmltocolor(params.Values['color']);
end
else if Uppercase(Tag) = '/FONT' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H1' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 6;
end
else if Uppercase(Tag) = '/H1' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H2' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 9;
end
else if Uppercase(Tag) = '/H2' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H3' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 12;
end
else if Uppercase(Tag) = '/H3' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H4' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 15;
end
else if Uppercase(Tag) = '/H4' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H5' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 18;
end
else if Uppercase(Tag) = '/H5' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H6' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 22;
end
else if Uppercase(Tag) = '/H6' then
popFontstack(fo_stk, cfont)
else {// Die H-Tags-�berschriften } if Uppercase(Tag) = 'H7' then
begin
// Schrift auf fontstack sichern
pushFontstack(fo_stk, cfont);
cfont.Size := 27;
end
else if Uppercase(Tag) = '/H7' then
popFontstack(fo_stk, cfont)
else // Bold-Tag
if Uppercase(Tag) = 'B' then
cfont.Style := cfont.Style + [fsbold]
else if Uppercase(Tag) = '/B' then
cfont.Style := cfont.Style - [fsbold]
else // Italic-Tag
if Uppercase(Tag) = 'I' then
cfont.Style := cfont.Style + [fsitalic]
else if Uppercase(Tag) = '/I' then
cfont.Style := cfont.Style - [fsitalic]
else // underline-Tag
if Uppercase(Tag) = 'U' then
cfont.Style := cfont.Style + [fsunderline]
else if Uppercase(Tag) = '/U' then
cfont.Style := cfont.Style - [fsunderline]
else // underline-Tag
if Uppercase(Tag) = 'UL' then
liste := True
else if Uppercase(Tag) = '/UL' then
begin
liste := False;
rtf.Lines.Add('');
Inc(row);
rtf.Lines.Add('');
Inc(row);
end
else // BR - Breakrow tag
if (Uppercase(Tag) = 'BR') or (Uppercase(Tag) = 'LI')
then
begin
rtf.Lines.Add('');
Inc(row);
end;
// unbekanntes tag als text ausgeben
// else rtf.Lines[row]:=RTF.lines[row]+'<'+tag+' '+tagparams+'>';
fo_pos.Add(IntToStr(rtf.selstart));
fo_cnt[fo_pos.Count] := TFont.Create;
fo_cnt[fo_pos.Count].Assign(cfont);
fo_liste[fo_pos.Count] := liste;
end
else
begin
// Spezialzeichen �bersetzen
if html[i] = '&' then
Transformspecialchars(html, i);
if (Ord(html[i]) <> 13) and (Ord(html[i]) <> 10) then
rtf.Lines[row] := RTF.Lines[row] + html[i];
end;
Inc(i);
until i >= Length(html);
// dummy eintragen
fo_pos.Add('999999');
// Den fertigen Text formatieren
for i := 0 to fo_pos.Count - 2 do
begin
rtf.SelStart := StrToInt(fo_pos[i]);
rtf.SelLength := StrToInt(fo_pos[i + 1]) - rtf.SelStart;
rtf.SelAttributes.Style := fo_cnt[i + 1].Style;
rtf.SelAttributes.Size := fo_cnt[i + 1].Size;
rtf.SelAttributes.Color := fo_cnt[i + 1].Color;
// die font wieder freigeben;
fo_cnt[i + 1].Free;
end;
// die Paragraphen also Listen setzen
i := 0;
while i <= fo_pos.Count - 2 do
begin
if fo_liste[i + 1] then
begin
rtf.SelStart := StrToInt(fo_pos[i + 1]);
while fo_liste[i + 1] do
Inc(i);
rtf.SelLength := StrToInt(fo_pos[i - 1]) - rtf.SelStart;
rtf.Paragraph.Numbering := nsBullet;
end;
Inc(i);
end;
rtf.Lines.EndUpdate;
Params.Free;
cfont.Free;
rtf.WordWrap := wordwrap;
FreeFontStack(fo_stk);
end;
2004. április 16., péntek
Drawing a line without using the LineTo function
Problem/Question/Abstract:
How can I draw a line without using the LineTo function?
Answer:
{
Enables you do draw a line if for some reason you
cannot use the delphi LineTo procedure.
For example, for drawing higher resolution lines
or drawing lines in 2D arrays.
}
procedure DrawLine(APoint1, APoint2: TPoint; ACanvas: TCanvas);
var
Lpixel, LMaxAxisLength: integer;
LRatio: Real;
begin
LMaxAxisLength := Max(abs(APoint1.X - APoint2.X), abs(APoint1.Y - APoint2.Y));
for Lpixel := 0 to LMaxAxisLength do
begin
LRatio := Lpixel / LMaxAxisLength;
ACanvas.Pixels[APoint1.X + Round((APoint2.X - APoint1.X) * LRatio),
APoint1.Y + Round((APoint2.Y - APoint1.Y) * LRatio)] :=
ACanvas.Pen.Color;
end;
end;
// Draw a double resolution line
procedure DrawLineDouble(APoint1, APoint2: TPoint; ACanvas: TCanvas);
var
Lpixel, LMaxAxisLength: integer;
LRatio: Real;
LPoint: TPoint;
begin
LMaxAxisLength := max(abs(APoint1.X - APoint2.X), abs(APoint1.Y - APoint2.Y));
for Lpixel := 0 to LMaxAxisLength do
begin
LRatio := Lpixel / LMaxAxisLength;
LPoint.X := APoint1.X + Round((APoint2.X - APoint1.X) * LRatio);
LPoint.Y := APoint1.Y + Round((APoint2.Y - APoint1.Y) * LRatio);
with ACAnvas do
begin
Pixels[LPoint.X * 2, LPoint.Y * 2] := clBlack;
Pixels[(LPoint.X * 2) + 1, LPoint.Y * 2] := clBlack;
Pixels[LPoint.X * 2, (LPoint.Y * 2) + 1] := clBlack;
Pixels[(LPoint.X * 2) + 1, (LPoint.Y * 2) + 1] := clBlack;
end;
end;
end;
How can I draw a line without using the LineTo function?
Answer:
{
Enables you do draw a line if for some reason you
cannot use the delphi LineTo procedure.
For example, for drawing higher resolution lines
or drawing lines in 2D arrays.
}
procedure DrawLine(APoint1, APoint2: TPoint; ACanvas: TCanvas);
var
Lpixel, LMaxAxisLength: integer;
LRatio: Real;
begin
LMaxAxisLength := Max(abs(APoint1.X - APoint2.X), abs(APoint1.Y - APoint2.Y));
for Lpixel := 0 to LMaxAxisLength do
begin
LRatio := Lpixel / LMaxAxisLength;
ACanvas.Pixels[APoint1.X + Round((APoint2.X - APoint1.X) * LRatio),
APoint1.Y + Round((APoint2.Y - APoint1.Y) * LRatio)] :=
ACanvas.Pen.Color;
end;
end;
// Draw a double resolution line
procedure DrawLineDouble(APoint1, APoint2: TPoint; ACanvas: TCanvas);
var
Lpixel, LMaxAxisLength: integer;
LRatio: Real;
LPoint: TPoint;
begin
LMaxAxisLength := max(abs(APoint1.X - APoint2.X), abs(APoint1.Y - APoint2.Y));
for Lpixel := 0 to LMaxAxisLength do
begin
LRatio := Lpixel / LMaxAxisLength;
LPoint.X := APoint1.X + Round((APoint2.X - APoint1.X) * LRatio);
LPoint.Y := APoint1.Y + Round((APoint2.Y - APoint1.Y) * LRatio);
with ACAnvas do
begin
Pixels[LPoint.X * 2, LPoint.Y * 2] := clBlack;
Pixels[(LPoint.X * 2) + 1, LPoint.Y * 2] := clBlack;
Pixels[LPoint.X * 2, (LPoint.Y * 2) + 1] := clBlack;
Pixels[(LPoint.X * 2) + 1, (LPoint.Y * 2) + 1] := clBlack;
end;
end;
end;
2004. április 15., csütörtök
Safety Design with a Static Instance
Problem/Question/Abstract:
The Singelton Pattern is widely used, on the other side OP lacks of statics, means one instance for all classes. No problem with the following design which acts like a time-server.
Answer:
Sometimes operations are performed on a class itself, rather than on instances of a class (that is, objects). This happens, for example, when you call a constructor method using a class reference.
TTimeKeeper = class;
TTimeKeeperClass = class of TTimeKeeper;
You can always refer to a specific class using its name, but at times it is necessary to declare variables or parameters that take classes as values, and in these situations you need class-reference types.
In our case we need a class-method and a global function too to get the one and only instance:
class function Instance: TTimeKeeper;
function TimeKeeper: TTimeKeeper; //global function
When this function is called, a safety instance is returned:
function TimeKeeper: TTimeKeeper;
begin
Result := TTimeKeeper.Instance;
end;
A class method is a method (other than a constructor) that operates on classes instead of objects. The definition of a class method must begin with the reserved word class. A class method can be called through a class reference or an object reference.
So the client calls the class method first:
procedure TMainDlg.NewBtnClick(Sender: TObject);
var
myTimer: TTimeKeeper;
begin
myTimer := TimeKeeper;
StatusBar.Panels[0].Text := timeToStr(myTimer.now);
end;
And the class method returns the protected and local instance:
class function TTimeKeeper.Instance: TTimeKeeper;
// Single Instance function - create when first needed
begin
Assert(Assigned(TimeKeeperClass));
if not Assigned(TimeKeeperInstance) then
TimeKeeperInstance := TimeKeeperClass.SingletonCreate;
Result := TimeKeeperInstance;
end;
unit SafetyTimeKeeper;
interface
uses
SysUtils;
type
ESingleton = class(Exception);
TInvalidateDestroy = class(TObject)
protected
class procedure SingletonError;
public
destructor Destroy; override;
end;
TTimeKeeper = class;
TTimeKeeperClass = class of TTimeKeeper;
TTimeKeeper = class(TInvalidateDestroy)
private
class procedure Shutdown;
function GetTime: TDateTime;
function GetDate: TDateTime;
function GetNow: TDateTime;
protected
// Allow descendents to set a new class for the instance:
class procedure SetTimeKeeperClass(aTimeKeeperClass: TTimeKeeperClass);
// Actual constructor and destructor that will be used:
constructor SingletonCreate; virtual;
destructor SingletonDestroy; virtual;
public
// Not for use - for obstruction only:
class procedure Create;
class procedure Free(Dummy: integer);
{$IFNDEF VER120}{$WARNINGS OFF}{$ENDIF}
// This generates warning in D3. D4 has reintroduce keyword to solve this
class procedure Destroy(Dummy: integer);
{$IFDEF VER120} reintroduce;
{$ENDIF}
// Simple interface:
class function Instance: TTimeKeeper;
property Time: TDateTime read GetTime;
property Date: TDateTime read GetDate;
property Now: TDateTime read GetNow;
end;
{$IFNDEF VER120}{$WARNINGS ON}{$ENDIF}
function TimeKeeper: TTimeKeeper;
implementation
class procedure TInvalidateDestroy.SingletonError;
// Raise an exception in case of illegal use
begin
raise ESingleton.CreateFmt('Illegal use of %s singleton instance!', [ClassName]);
end;
destructor TInvalidateDestroy.Destroy;
// Protected against use of default destructor
begin
SingletonError;
end;
{ TTimeKeeper }
var
TimeKeeperInstance: TTimeKeeper = nil;
TimeKeeperClass: TTimeKeeperClass = TTimeKeeper;
class procedure TTimeKeeper.SetTimeKeeperClass(aTimeKeeperClass: TTimeKeeperClass);
// Allow change of instance class
begin
Assert(Assigned(aTimeKeeperClass));
if Assigned(TimeKeeperInstance) then
SingletonError;
TimeKeeperClass := aTimeKeeperClass;
end;
class function TTimeKeeper.Instance: TTimeKeeper;
// Single Instance function - create when first needed
begin
Assert(Assigned(TimeKeeperClass));
if not Assigned(TimeKeeperInstance) then
TimeKeeperInstance := TimeKeeperClass.SingletonCreate;
Result := TimeKeeperInstance;
end;
class procedure TTimeKeeper.Shutdown;
// Time to close down the show
begin
if Assigned(TimeKeeperInstance) then
begin
TimeKeeperInstance.SingletonDestroy;
TimeKeeperInstance := nil;
end;
end;
constructor TTimeKeeper.SingletonCreate;
// Protected constructor
begin
inherited Create;
end;
destructor TTimeKeeper.SingletonDestroy;
// Protected destructor
begin
// We cannot call inherited Destroy; here!
// It would raise an ESingleton exception
end;
// Protected against use of default constructor
class procedure TTimeKeeper.Create;
begin
SingletonError;
end;
// Protected against use of Free
class procedure TTimeKeeper.Free(Dummy: integer);
begin
SingletonError;
end;
class procedure TTimeKeeper.Destroy(Dummy: integer);
begin
SingletonError;
end;
// Property access methods
function TTimeKeeper.GetDate: TDateTime;
begin
Result := SysUtils.Date;
end;
function TTimeKeeper.GetNow: TDateTime;
begin
Result := SysUtils.Now;
end;
function TTimeKeeper.GetTime: TDateTime;
begin
Result := SysUtils.Time;
end;
// Simplified functional interface
function TimeKeeper: TTimeKeeper;
begin
Result := TTimeKeeper.Instance;
end;
initialization
finalization
// Destroy when application closes
TTimeKeeper.Shutdown;
end.
The Singelton Pattern is widely used, on the other side OP lacks of statics, means one instance for all classes. No problem with the following design which acts like a time-server.
Answer:
Sometimes operations are performed on a class itself, rather than on instances of a class (that is, objects). This happens, for example, when you call a constructor method using a class reference.
TTimeKeeper = class;
TTimeKeeperClass = class of TTimeKeeper;
You can always refer to a specific class using its name, but at times it is necessary to declare variables or parameters that take classes as values, and in these situations you need class-reference types.
In our case we need a class-method and a global function too to get the one and only instance:
class function Instance: TTimeKeeper;
function TimeKeeper: TTimeKeeper; //global function
When this function is called, a safety instance is returned:
function TimeKeeper: TTimeKeeper;
begin
Result := TTimeKeeper.Instance;
end;
A class method is a method (other than a constructor) that operates on classes instead of objects. The definition of a class method must begin with the reserved word class. A class method can be called through a class reference or an object reference.
So the client calls the class method first:
procedure TMainDlg.NewBtnClick(Sender: TObject);
var
myTimer: TTimeKeeper;
begin
myTimer := TimeKeeper;
StatusBar.Panels[0].Text := timeToStr(myTimer.now);
end;
And the class method returns the protected and local instance:
class function TTimeKeeper.Instance: TTimeKeeper;
// Single Instance function - create when first needed
begin
Assert(Assigned(TimeKeeperClass));
if not Assigned(TimeKeeperInstance) then
TimeKeeperInstance := TimeKeeperClass.SingletonCreate;
Result := TimeKeeperInstance;
end;
unit SafetyTimeKeeper;
interface
uses
SysUtils;
type
ESingleton = class(Exception);
TInvalidateDestroy = class(TObject)
protected
class procedure SingletonError;
public
destructor Destroy; override;
end;
TTimeKeeper = class;
TTimeKeeperClass = class of TTimeKeeper;
TTimeKeeper = class(TInvalidateDestroy)
private
class procedure Shutdown;
function GetTime: TDateTime;
function GetDate: TDateTime;
function GetNow: TDateTime;
protected
// Allow descendents to set a new class for the instance:
class procedure SetTimeKeeperClass(aTimeKeeperClass: TTimeKeeperClass);
// Actual constructor and destructor that will be used:
constructor SingletonCreate; virtual;
destructor SingletonDestroy; virtual;
public
// Not for use - for obstruction only:
class procedure Create;
class procedure Free(Dummy: integer);
{$IFNDEF VER120}{$WARNINGS OFF}{$ENDIF}
// This generates warning in D3. D4 has reintroduce keyword to solve this
class procedure Destroy(Dummy: integer);
{$IFDEF VER120} reintroduce;
{$ENDIF}
// Simple interface:
class function Instance: TTimeKeeper;
property Time: TDateTime read GetTime;
property Date: TDateTime read GetDate;
property Now: TDateTime read GetNow;
end;
{$IFNDEF VER120}{$WARNINGS ON}{$ENDIF}
function TimeKeeper: TTimeKeeper;
implementation
class procedure TInvalidateDestroy.SingletonError;
// Raise an exception in case of illegal use
begin
raise ESingleton.CreateFmt('Illegal use of %s singleton instance!', [ClassName]);
end;
destructor TInvalidateDestroy.Destroy;
// Protected against use of default destructor
begin
SingletonError;
end;
{ TTimeKeeper }
var
TimeKeeperInstance: TTimeKeeper = nil;
TimeKeeperClass: TTimeKeeperClass = TTimeKeeper;
class procedure TTimeKeeper.SetTimeKeeperClass(aTimeKeeperClass: TTimeKeeperClass);
// Allow change of instance class
begin
Assert(Assigned(aTimeKeeperClass));
if Assigned(TimeKeeperInstance) then
SingletonError;
TimeKeeperClass := aTimeKeeperClass;
end;
class function TTimeKeeper.Instance: TTimeKeeper;
// Single Instance function - create when first needed
begin
Assert(Assigned(TimeKeeperClass));
if not Assigned(TimeKeeperInstance) then
TimeKeeperInstance := TimeKeeperClass.SingletonCreate;
Result := TimeKeeperInstance;
end;
class procedure TTimeKeeper.Shutdown;
// Time to close down the show
begin
if Assigned(TimeKeeperInstance) then
begin
TimeKeeperInstance.SingletonDestroy;
TimeKeeperInstance := nil;
end;
end;
constructor TTimeKeeper.SingletonCreate;
// Protected constructor
begin
inherited Create;
end;
destructor TTimeKeeper.SingletonDestroy;
// Protected destructor
begin
// We cannot call inherited Destroy; here!
// It would raise an ESingleton exception
end;
// Protected against use of default constructor
class procedure TTimeKeeper.Create;
begin
SingletonError;
end;
// Protected against use of Free
class procedure TTimeKeeper.Free(Dummy: integer);
begin
SingletonError;
end;
class procedure TTimeKeeper.Destroy(Dummy: integer);
begin
SingletonError;
end;
// Property access methods
function TTimeKeeper.GetDate: TDateTime;
begin
Result := SysUtils.Date;
end;
function TTimeKeeper.GetNow: TDateTime;
begin
Result := SysUtils.Now;
end;
function TTimeKeeper.GetTime: TDateTime;
begin
Result := SysUtils.Time;
end;
// Simplified functional interface
function TimeKeeper: TTimeKeeper;
begin
Result := TTimeKeeper.Instance;
end;
initialization
finalization
// Destroy when application closes
TTimeKeeper.Shutdown;
end.
2004. április 14., szerda
Add a horizontal scrollbar to a TListBox
Problem/Question/Abstract:
How to add a horizontal scrollbar to a TListBox
Answer:
A quick way to add the horizontal scroll bar and set its scroll range is to use SendMessage. Put the following command in the OnCreate or OnActivate methods to make the TListbox 300 pixels wide.
uses
ShellAPI
{ ... }
SendMessage(ListBox1.Handle, LB_SETHORIZONTALEXTENT, 300, 0);
{ ... }
How to add a horizontal scrollbar to a TListBox
Answer:
A quick way to add the horizontal scroll bar and set its scroll range is to use SendMessage. Put the following command in the OnCreate or OnActivate methods to make the TListbox 300 pixels wide.
uses
ShellAPI
{ ... }
SendMessage(ListBox1.Handle, LB_SETHORIZONTALEXTENT, 300, 0);
{ ... }
2004. április 13., kedd
Create a menu item into the Delphi menu?
Problem/Question/Abstract:
How to create a menu item into the Delphi menu?
Answer:
uses ToolsApi, Menus;
{....}
var
item: TMenuItem;
begin
{get reference to delphi's mainmenu. You can handle it like a common TMainMenu}
with (BorlandIDEServices as INTAServices).GetMainMenu do
begin
item := TMenuItem.Create(nil);
item.Caption := 'A Mewn caption';
Items.Add(item);
end;
end;
How to create a menu item into the Delphi menu?
Answer:
uses ToolsApi, Menus;
{....}
var
item: TMenuItem;
begin
{get reference to delphi's mainmenu. You can handle it like a common TMainMenu}
with (BorlandIDEServices as INTAServices).GetMainMenu do
begin
item := TMenuItem.Create(nil);
item.Caption := 'A Mewn caption';
Items.Add(item);
end;
end;
2004. április 12., hétfő
Check if the mouse cursor is outside a TForm
Problem/Question/Abstract:
How can I find out if the cursor is leaving a Delphi form?
Answer:
Solve 1:
Add a handler for the CM_MOUSELEAVE message to the form:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
private
{ Private declarations }
procedure CMMouseEnter(var msg: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var msg: TMessage); message CM_MOUSELEAVE;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.CMMouseEnter(var msg: TMessage);
begin
if msg.lparam = 0 then
memo1.Lines.add('Entered ' + Name)
else
memo1.Lines.add('Entered ' + TControl(msg.lparam).Name);
end;
procedure TForm1.CMMouseLeave(var msg: TMessage);
begin
if msg.lparam = 0 then
memo1.Lines.add('Left ' + Name)
else
memo1.Lines.add('Left ' + TControl(msg.lparam).Name);
end;
end.
Solve 2:
Place the following code in your form's OnMouseMove event handler, and you'll see SetCapture/ ReleaseCapture in action (plus its side-effects):
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if (GetCapture < > Handle) then {OnMouseEnter}
begin
Beep;
Caption := 'Hello';
SetCapture(Handle);
end
else if (PtInRect(ClientRect, Point(X, Y))) then {OnMouseOver}
Caption := 'X=' + IntToStr(X) + ':Y=' + IntToStr(Y)
else {OnMouseOut}
begin
Beep;
Caption := 'Goodbye!';
ReleaseCapture;
end;
end;
Solve 3:
You can use a timer (the smaller the interval the more sensitive the program) and in the OnTimer event handler control the mouse position to check if the mouse is inside or outside the form:
procedure TForm1.Timer1Timer(Sender: TObject);
var
pt: TPoint;
begin
GetCursorPos(pt);
if (pt.x < Left) or (pt.x > left + Width) then
Caption := 'Out'
else if (pt.y < Top) or (pt.y > Top + Height) then
Caption := 'Out'
else
Caption := 'In';
end;
How can I find out if the cursor is leaving a Delphi form?
Answer:
Solve 1:
Add a handler for the CM_MOUSELEAVE message to the form:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
private
{ Private declarations }
procedure CMMouseEnter(var msg: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var msg: TMessage); message CM_MOUSELEAVE;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.CMMouseEnter(var msg: TMessage);
begin
if msg.lparam = 0 then
memo1.Lines.add('Entered ' + Name)
else
memo1.Lines.add('Entered ' + TControl(msg.lparam).Name);
end;
procedure TForm1.CMMouseLeave(var msg: TMessage);
begin
if msg.lparam = 0 then
memo1.Lines.add('Left ' + Name)
else
memo1.Lines.add('Left ' + TControl(msg.lparam).Name);
end;
end.
Solve 2:
Place the following code in your form's OnMouseMove event handler, and you'll see SetCapture/ ReleaseCapture in action (plus its side-effects):
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if (GetCapture < > Handle) then {OnMouseEnter}
begin
Beep;
Caption := 'Hello';
SetCapture(Handle);
end
else if (PtInRect(ClientRect, Point(X, Y))) then {OnMouseOver}
Caption := 'X=' + IntToStr(X) + ':Y=' + IntToStr(Y)
else {OnMouseOut}
begin
Beep;
Caption := 'Goodbye!';
ReleaseCapture;
end;
end;
Solve 3:
You can use a timer (the smaller the interval the more sensitive the program) and in the OnTimer event handler control the mouse position to check if the mouse is inside or outside the form:
procedure TForm1.Timer1Timer(Sender: TObject);
var
pt: TPoint;
begin
GetCursorPos(pt);
if (pt.x < Left) or (pt.x > left + Width) then
Caption := 'Out'
else if (pt.y < Top) or (pt.y > Top + Height) then
Caption := 'Out'
else
Caption := 'In';
end;
2004. április 11., vasárnap
Resize a TForm in steps
Problem/Question/Abstract:
How can I resize a form in steps, not smooth, like the Object Inspector in Delphi?
Answer:
First, declare a message handler for the WM_SIZING message in your form:
TForm1 = class(TForm)
{ ... }
protected
procedure WmSizing(var Msg: TMessage); message WM_SIZING;
{ ... }
end;
Then define the WmSizing message handler like so:
procedure TForm1.WmSizing(var Msg: TMessage);
const
STEP = 20;
var
Side: LongInt;
Rect: PRect;
begin
inherited;
Side := Msg.WParam;
Rect := PRect(Msg.LParam);
if (WMSZ_BOTTOM and Side = WMSZ_BOTTOM) then
Rect^.Bottom := Rect^.Bottom - (Rect^.Bottom mod STEP);
if (WMSZ_BOTTOMLEFT and Side = WMSZ_BOTTOMLEFT) then
begin
Rect^.Bottom := Rect^.Bottom - (Rect^.Bottom mod STEP);
Rect^.Left := Rect^.Left - (Rect^.Left mod STEP);
end;
if (WMSZ_BOTTOMRIGHT and Side = WMSZ_BOTTOMRIGHT) then
begin
Rect^.Bottom := Rect^.Bottom - (Rect^.Bottom mod STEP);
Rect^.Right := Rect^.Right - (Rect^.Right mod STEP);
end;
if (WMSZ_LEFT and Side = WMSZ_LEFT) then
Rect^.Left := Rect^.Left - (Rect^.Left mod STEP);
if (WMSZ_RIGHT and Side = WMSZ_RIGHT) then
Rect^.Right := Rect^.Right - (Rect^.Right mod STEP);
if (WMSZ_TOP and Side = WMSZ_TOP) then
Rect^.Top := Rect^.Top - (Rect^.Top mod STEP);
if (WMSZ_TOPLEFT and Side = WMSZ_TOPLEFT) then
begin
Rect^.Top := Rect^.Top - (Rect^.Top mod STEP);
Rect^.Left := Rect^.Left - (Rect^.Left mod STEP);
end;
if (WMSZ_TOPRIGHT and Side = WMSZ_TOPRIGHT) then
begin
Rect^.Top := Rect^.Top - (Rect^.Top mod STEP);
Rect^.Right := Rect^.Right - (Rect^.Right mod STEP);
end;
Msg.Result := 1;
end;
You can adjust the STEP constant to meet your needs. Likewise, you can make any edge a constant size simply by assigning a valueto it.
2004. április 10., szombat
SCSI-2 device serial number
Problem/Question/Abstract:
For IDE harddisk you can use S.M.A.R.T. API function for extracting serial number. For SCSI it does not work.
Answer:
program ScsiSN;
// PURPOSE: Simple console application that display SCSI harddisk serial number
{$APPTYPE CONSOLE}
uses
Windows, SysUtils;
//-------------------------------------------------------------
function GetDeviceHandle(sDeviceName: string): THandle;
begin
Result := CreateFile(PChar('\\.\' + sDeviceName),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, 0, 0)
end;
//-------------------------------------------------------------
function ScsiHddSerialNumber(DeviceHandle: THandle): string;
{$ALIGN ON}
type
TScsiPassThrough = record
Length: Word;
ScsiStatus: Byte;
PathId: Byte;
TargetId: Byte;
Lun: Byte;
CdbLength: Byte;
SenseInfoLength: Byte;
DataIn: Byte;
DataTransferLength: ULONG;
TimeOutValue: ULONG;
DataBufferOffset: DWORD;
SenseInfoOffset: ULONG;
Cdb: array[0..15] of Byte;
end;
TScsiPassThroughWithBuffers = record
spt: TScsiPassThrough;
bSenseBuf: array[0..31] of Byte;
bDataBuf: array[0..191] of Byte;
end;
{ALIGN OFF}
var
dwReturned: DWORD;
len: DWORD;
Buffer: array[0..SizeOf(TScsiPassThroughWithBuffers) +
SizeOf(TScsiPassThrough) - 1] of Byte;
sptwb: TScsiPassThroughWithBuffers absolute Buffer;
begin
Result := '';
FillChar(Buffer, SizeOf(Buffer), #0);
with sptwb.spt do
begin
Length := SizeOf(TScsiPassThrough);
CdbLength := 6; // CDB6GENERIC_LENGTH
SenseInfoLength := 24;
DataIn := 1; // SCSI_IOCTL_DATA_IN
DataTransferLength := 192;
TimeOutValue := 2;
DataBufferOffset := PChar(@sptwb.bDataBuf) - PChar(@sptwb);
SenseInfoOffset := PChar(@sptwb.bSenseBuf) - PChar(@sptwb);
Cdb[0] := $12; // OperationCode := SCSIOP_INQUIRY;
Cdb[1] := $01; // Flags := CDB_INQUIRY_EVPD; Vital product data
Cdb[2] := $80; // PageCode Unit serial number
Cdb[4] := 192; // AllocationLength
end;
len := sptwb.spt.DataBufferOffset + sptwb.spt.DataTransferLength;
if DeviceIoControl(DeviceHandle, $0004D004, @sptwb, SizeOf(TScsiPassThrough),
@sptwb, len, dwReturned, nil)
and ((PChar(@sptwb.bDataBuf) + 1)^ = #$80) then
SetString(Result, PChar(@sptwb.bDataBuf) + 4,
Ord((PChar(@sptwb.bDataBuf) + 3)^));
end;
//=============================================================
var
hDevice: THandle = 0;
sSerNum, sDeviceName: string;
begin
sDeviceName := ParamStr(1);
if sDeviceName = '' then
begin
WriteLn;
WriteLn('Display SCSI-2 device serial number.');
WriteLn;
WriteLn('Using:');
WriteLn;
if Win32Platform = VER_PLATFORM_WIN32_NT then // Windows NT/2000
WriteLn(' ScsiSN PhysicalDrive0')
else
WriteLn(' ScsiSN C:');
WriteLn(' ScsiSN Cdrom0');
WriteLn(' ScsiSN Tape0');
WriteLn;
Exit;
end;
hDevice := GetDeviceHandle(sDeviceName);
if hDevice = INVALID_HANDLE_VALUE then
WriteLn('Error on GetDeviceHandle: ', SysErrorMessage(GetLastError))
else
try
sSerNum := ScsiHddSerialNumber(hDevice);
if sSerNum = '' then
WriteLn('Error on DeviceIoControl: ',
SysErrorMessageGetLastError))
else
WriteLn('Device ' + sDeviceName
+ ' serial number = "', sSerNum, '"');
finally
CloseHandle(hDevice);
end;
end.
For more information about SCSI commands:
ftp://ftp.t10.org/t10/drafts/scsi-1/
ftp://ftp.t10.org/t10/drafts/spc/
ftp://ftp.t10.org/t10/drafts/spc2/
2004. április 9., péntek
Eject and close CD-Drive
Problem/Question/Abstract:
Eject and close CD-Drive
Answer:
These two function calls open and close the CD tray.
Because the command "wait" is included in the command string, the function returns after the command has been executed:
uses
MMSystem;
{ open the CD tray }
mciSendString('Set cdaudio door open wait', nil, 0, 0);
{ close the CD tray }
mciSendString('Set cdaudio door closed wait', nil, 0, 0);
2004. április 8., csütörtök
How to detect if a TMemo has been scrolled
Problem/Question/Abstract:
Is there a way of finding out - during or immediately after the fact - that a control has been scrolled? For instance, say someone moves the scroll thumb in a TMemo. Is there a message I can intercept that says this occurred? I don't really need to know which direction or by how much, just that it happened.
Answer:
Here's unit that shows one way to do this without having to create a descendent. It will let you know about "direct" scrolls, but not about scrolls that happen because of cursor movement through the memo's text, etc. It will also report a scroll if the user merely clicked on the thumb track without moving it (without actually scrolling).
To see the code in action, you will need to fill a TMemo with enough text so that it is necessary to scroll.
unit ScrollCatchU;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
ClearButton: TButton;
ScrolledLabel: TLabel;
procedure FormCreate(Sender: TObject);
procedure ClearButtonClick(Sender: TObject);
private
Counter: cardinal;
procedure Memo1ScrollCatcher(var Message: TMessage);
public
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
type
TMyControl = class(TControl);
procedure TForm1.Memo1ScrollCatcher(var Message: TMessage);
begin
Inc(Counter); {for testing/ diagnostics only ...}
{Add commented out section below, if you only want the "last" scroll
message in a sequence}
if ((Message.Msg = WM_VSCROLL) or (Message.Msg = WM_HSCROLL))
{ and (TWMVScroll(Message).ScrollCode = SB_ENDSCROLL) }then
ScrolledLabel.caption := 'Scrolled';
{ caption := format('Message: %d ScrollCode: %d Counter: %d', [Message.Msg,
TWMVScroll(Message).ScrollCode, Counter]); }
TMyControl(Memo1).WndProc(Message);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.WindowProc := Memo1ScrollCatcher;
Counter := 0;
ClearButtonClick(nil);
end;
procedure TForm1.ClearButtonClick(Sender: TObject);
begin
ScrolledLabel.Caption := '';
{Using a manual "reset" for the "Scrolled" display}
end;
end.
This technique can be used with any TControl descendent.
You might want to add the Windows Mouse Wheel message to the ones that routine is looking for. Something like:
{ ... }
if ((Message.Msg = WM_VSCROLL) or (Message.Msg = WM_HSCROLL)
or (Message.Msg = WM_MOUSEWHEEL))
{and (TWMVScroll(Message).ScrollCode = SB_ENDSCROLL)}then
ScrolledLabel.caption := 'Scrolled';
{ ... }
Of course, if you are just fishing for the SB_ENDSCROLL ScrollCode with the other messages, you'll have to separate the test for this message out a little further.
Feliratkozás:
Bejegyzések (Atom)