I'm trying to print directly to a printer using esc/p commands (EPSON TM-T70) without using printer driver. Code found here.
However, if I try to print any strings, they are truncated. For example:
MyPrinter := TRawPrint.Create(nil);
try
MyPrinter.DeviceName := 'EPSON TM-T70 Receipt';
MyPrinter.JobName := 'MyJob';
if MyPrinter.OpenDevice then
begin
MyPrinter.WriteString('This is page 1');
MyPrinter.NewPage;
MyPrinter.WriteString('This is page 2');
MyPrinter.CloseDevice;
end;
finally
MyPrinter.Free;
end;
Would print only "This isThis is"! I wouldn't ordinarily use MyPrinter.NewPage to send a line break command, but regardless, why does it truncates the string?
Also notice in RawPrint unit WriteString function:
Result := False;
if IsOpenDevice then begin
Result := True;
if not WritePrinter(hPrinter, PChar(Text), Length(Text), WrittenChars) then begin
RaiseError(GetLastErrMsg);
Result := False;
end;
end;
If I put a breakpoint there and step through the code, then WrittenChars is set to 14, which is correct. Why does it act like that?
You are using a unicode-enabled version of Delphi. Chars are 2 bytes long. When you call your function with Length(s) you're sending the number of chars, but the function probably expects the size of the buffer. Replace it with SizeOf(s) Length(s)*SizeOf(Char).
Since the size of one unicode char is exactly 2 bytes, when you're sending Length when buffer size is required, you're essentially telling the API to only use half the buffer. Hence all strings are aproximately split in half.
Maybe you can use the ByteLength function which gives the length of a string in bytes.
Related
With this code to retrieve the version of the installed MS Word:
uses uses oleauto;
[...]
function TForm2.GetWordVersion:string;
const
wdDoNotSaveChanges = 0;
var
WordApp: OLEVariant;
WordVersion: variant;
begin
Try
WordApp := CreateOLEObject('Word.Application');
WordVersion := WordApp.version;
WordApp.Quit(wdDoNotSaveChanges);
except
on E: Exception do
begin
WordVersion := -1;
end;
End;
Result := wordversion;
end;
I get 140 on my machine, my colleague gets 14. Both are win7/Word2010 but I am in Italy he is in India.
Anyone knows about this?
Why different values?
Thanks
I'm guessing this is a decimal separator issue. Word returns the string '14.0' and then when you convert to integer the period is treated as a positional separator on one machine, and a decimal separator on another.
The solution is to stop converting to integer which I infer that you are doing in code that you have not shown.
I am inferring that from this comment:
I can convert it to string and use the first 2 chars.
Since the code in the question operates on strings, I conclude that other code, not shown in the question, is converting to integer.
I am trying to write and read a non-fixed string using TFileStream. I am getting an access violation error though. Here is my code:
// Saving a file
(...)
count:=p.Tags.Count; // Number of lines to save (Tags is a TStringList)
FS.Write(count, SizeOf(integer));
for j := 0 to p.Tags.Count-1 do
begin
str:=p.Tags.Strings[j];
tmp:=Length(str)*SizeOf(char);
FS.Write(tmp, SizeOf(Integer));
FS.Write(str[1], Length(str)*SizeOf(char));
end;
// Loading a file
(...)
p.Tags.Add('hoho'); // Check if Tags is created. This doesn't throw an error.
Read(TagsCount, SizeOf(integer)); // Number of lines to read
for j := 0 to TagsCount-1 do
begin
Read(len, SizeOf(Integer)); // length of this line of text
SetLength(str, len); // don't know if I have to do this
Read(str, len); // No error, but str has "inaccessible value" in watch list
p.Tags.Add(str); // Throws error
end;
The file seems to save just fine, when I open it with a hexeditor, I can find the right strings saved there, but loading is throwing errors.
Could you help me out?
You save the number of bytes, and that's how many bytes you write. When you read the value, you treat it as the number of characters, and then read that many bytes. That won't cause the problem you're seeing now, though, since you're making the buffer bigger than it needs to be as of Delphi 2009.
The problem is that you're reading into the string variable, not the string's contents. You used str[1] when writing; do the same when reading. Otherwise, you're overwriting the string reference that you allocated when you called SetLength.
Read(nBytes, SizeOf(Integer));
nChars := nBytes div SieOf(Char);
SetLength(str, nChars);
Read(str[1], nBytes);
And yes, you do need to call SetLength. Read doesn't know what its reading into, so it has no way of knowing that it needs to set the size to anything in advance.
When transitioning from Delphi 2006 to Delphi XE2, one of the things that we learned is that RichEdit 2.0 replaces internally CRLF pairs with a single CR character. This has the unfortunate effect of throwing off all character index calculations based on the actual text string on the VCL's side.
The behavior I can see by tracing through the VCL code is as follows:
Sending a WM_GETTEXT message (done in TControl.GetTextBuf) will return a text buffer that contains CRLF pairs.
Sending a WM_GETTEXTLENGTH message (done in TControl.GetTextLen) will return a value as if the text still contains CRLF characters.
In contrast, sending an EM_SETSELEX message (i.e. setting SelStart) will treat the input value as if the text contains only CR characters.
This causes all sorts of things to fail (such as syntax highlighting) in our application. As you can tell, everything is off by exactly one character for every new line up to that point.
Obviously, since this is inconsistent behavior, we must be missing something or doing something very wrong.
Does anybody else has any experience with the transition from a RichEdit 1.0 to a RichEdit 2.0 control and how did you solve this issue? Finally, is there any way to force RichEdit 2.0 to use CRLF pairs just like RichEdit 1.0?
We also ran into this very issue.
We do a "mail merge" type of thing where we have templates with merge codes that are parsed and replaced by data from outside sources.
This index mismatch between pos(mystring, RichEdit.Text) and the positioning index into the RichEdit text using RichText.SelStart broke our merge.
I don't have a good answer but I came up with a workaround. It's a bit cumbersome (understatment!) but until a better solution comes along...
The workaround is to use a hidden TMemo and copy the RichEdit text to it and change the CR/LF pairs to CR only. Then use the TMemo to find the proper positioning using pos(string, TMemo) and use that to get the selstart position to use in the TRichEdit.
This really sucks but hopefully this workaround will help others in our situation or maybe spark somebody smarter than me into coming up with a better solution.
I'll show a little sample code...
Since we are replacing text using seltext we need to replace text in BOTH the RichEdit control and the TMemo control to keep the two synchronized.
StartToken and EndToken are the merge code delimiters and are a constant.
function TEditForm.ParseTest: boolean;
var TagLength: integer;
var ValueLength: integer;
var ParseStart: integer;
var ParseEnd: integer;
var ParseValue: string;
var Memo: TMemo;
begin
Result := True;//Default
Memo := TMemo.Create(nil);
try
Memo.Parent := self;
Memo.Visible := False;
try
Memo.Lines.Clear;
Memo.Lines.AddStrings(RichEditor.Lines);
Memo.Text := stringreplace(Memo.Text,#13#10,#13,[rfReplaceAll]);//strip CR/LF pairs and replace with CR
while (Pos(StartToken, Memo.Text) > 0) and (Pos(EndToken, Memo.Text) > 0) do begin
ParseStart := Pos(StartToken, Memo.SelText);
ParseEnd := Pos(EndToken, Memo.SelText) + Length(EndToken);
if ParseStart >= ParseEnd then begin//oops, something's wrong - bail out
Result := true;
myEditor.SelStart := 0;
exit;
end;
TagLength := ParseEnd - ParseStart;
ValueLength := (TagLength - Length(StartToken)) - Length(EndToken);
ParseValue := Copy(Memo.SelText, (ParseStart + Length(StartToken)), ValueLength);
Memo.selstart := ParseStart - 1; //since the .text is zero based, but pos is 1 based we subtract 1
Memo.sellength := TagLength;
RichEditor.selstart := ParseStart - 1; //since the .text is zero based, but pos is 1 based we subtract 1
RichEditor.sellength := TagLength;
TempText := GetValue(ParseValue);
Memo.SelText := TempText;
RichEditor.SelText := TempText;
end;
except
on e: exception do
begin
MessageDlg(e.message,mtInformation,[mbOK],0);
result := false;
end;
end;//try..except
finally
FreeAndNil(Memo);
end;
end;
How about subtracting EM_LINEFROMCHAR from the caret position? (OR the position of EM_GETSEL) whichever you need.
You could even get two EM_LINEFROMCHAR variables. One from the selection start and the other from the desired caret/selection position, if you only want to know how many cl/cr pairs are in the selection.
I want to convert a large 64 bit value from decimal or hex string to 64 bit UINT64 data type. There is a UIntToStr to help converting the UINT64 to string, but no way to convert a 64 bit integer to a unsigned value, as a string. That means integer values greater than 2**63 can not be represented in decimal or hex, using the RTL. This is normally not a big deal, but it can happen that a user needs to input a value, as an unsigned integer, which must be stored into the registry as a 64 bit unsigned integer value.
procedure HandleLargeHexValue;
var
x:UINT64;
begin
x := $FFFFFFFFFFFFFFFE;
try
x := StrToInt('$FFFFFFFFFFFFFFFF'); // range error.
except
x := $FFFFFFFFFFFFFFFD;
end;
Caption := UintToStr(x);
end;
Update Val now works fine in Delphi XE4 and up. In XE3 and below Val('$FFFFFFFFFFFFFFFF') works but not Val('9223372036854775899'). As Roeland points out below in Quality Central 108740: System.Val had problems with big UInt64 values in decimal until Delphi XE4.
UPDATE: In XE4 and later the RTL bug was fixed. This hack is only useful in Delphi XE3 or older
Well, if it ain't there, I guess I could always write it.
(I wrote a pretty good unit test for this too, but its too big to post here)
unit UIntUtils;
{ A missing RTL function written by Warren Postma. }
interface
function TryStrToUINT64(StrValue:String; var uValue:UInt64 ):Boolean;
function StrToUINT64(Value:String):UInt64;
implementation
uses SysUtils,Character;
{$R-}
function TryStrToUINT64(StrValue:String; var uValue:UInt64 ):Boolean;
var
Start,Base,Digit:Integer;
n:Integer;
Nextvalue:UInt64;
begin
result := false;
Base := 10;
Start := 1;
StrValue := Trim(UpperCase(StrValue));
if StrValue='' then
exit;
if StrValue[1]='-' then
exit;
if StrValue[1]='$' then
begin
Base := 16;
Start := 2;
if Length(StrValue)>17 then // $+16 hex digits = max hex length.
exit;
end;
uValue := 0;
for n := Start to Length(StrValue) do
begin
if Character.IsDigit(StrValue[n]) then
Digit := Ord(StrValue[n])-Ord('0')
else if (Base=16) and (StrValue[n] >= 'A') and (StrValue[n] <= 'F') then
Digit := (Ord(StrValue[n])-Ord('A'))+10
else
exit;// invalid digit.
Nextvalue := (uValue*base)+digit;
if (Nextvalue<uValue) then
exit;
uValue := Nextvalue;
end;
result := true; // success.
end;
function StrToUINT64(Value:String):UInt64;
begin
if not TryStrToUINT64(Value,result) then
raise EConvertError.Create('Invalid uint64 value');
end;
end.
I must disagree that Val solves this issue.
Val works only for big UInt64 values when they are written in Hex. When they are written in decimal, the last character is removed from the string and the resulting value is wrong.
See Quality Central 108740: System.Val has problems with big UInt64 values
EDIT: It seems that this issue should be solved in XE4. Can't test this.
With Value a UINT64, the code snippet below gives the expected answer on Delphi 2010 but only if the input values are in hexadecimal
stringValue := '$FFFFFFFFFFFFFFFF';
val( stringValue, value, code );
ShowMessage( UIntToStr( value ));
I'd simply wrap val in a convenience function and you're done.
Now feel free to burn me. Am I missing a digit in my tests? :D
I'm having a problem saving a vary large database type in Delphi. It contains an array[1..3500] of TItem, which in turn has two arrays[1..50] and [1..20]. I get a stack overflow unless I set the variable as a Pointer and use the GetMem, FreeMem commands below, but then I can't save it. Code is below.
procedure TDatabase.SaveDB;
var
TempDB: ^TSaveDB;
K, X: integer;
sComment, sTitle, sComposer, sISDN, sCategory: string;
begin
GetMem(TempDB, SizeOf(TSaveDB));
TempDB.CatCount := fCategoryCount;
TempDB.ItemCount := fItemCount;
for K := 1 to fCategoryCount do
TempDB.Categories[K] := fCategories[K];
for K := 1 to fItemCount do
begin
fItems[K].ReturnSet(sTitle, sComposer, sCategory, sISDN, sComment);
with TempDB.Items[K] do
begin
Title := sTitle;
Composer := sComposer;
Category := sCategory;
ISDN := sISDN;
end;
TempDB.Items[K].Comments[1] := Copy(sComment, 1, 255);
Delete(sComment, 1, 255);
TempDB.Items[K].Comments[2] := Copy(sComment, 1, 255);
Delete(sComment, 1, 255);
TempDB.Items[K].Comments[3] := Copy(sComment, 1, 255);
Delete(sComment, 1, 255);
TempDB.Items[K].Comments[4] := Copy(sComment, 1, 255);
Delete(sComment, 1, 255);
TempDB.Items[K].KeyWCount := fItems[K].GetKeyCount;
for X := 1 to fItems[K].GetKeyCount do
TempDB.Items[K].Keywords[X] := fItems[K].GetKeywords(X);
end;
AssignFile(DBSave, fSaveName);
Rewrite(DBSave);
Write(DBSave, TempDB);
Closefile(dBSave);
FreeMem(TempDB, sizeof(TSaveDB));
end;
Use GetMem or SetLength or TList/TObjectList and write to the file one TSaveDB at a time. Or
change the file type and use BlockWrite to write it all at once. Or even better: use TFileStream.
Your problem is in the "write" statement. Doing things with arbitrary pointers leads to all sorts of strange behavior. You'd have it a lot easier if you rewrote this using a TFileStream instead of the current approach.
To expand on Mason's answer:
NEVER read or write a pointer, period. It would take a major stroke of luck to get anything reasonable out of doing it and in the real world when you're not just running your program again the odds of success go from infinitesimal to zero.
Rather, you need to read and write what the pointer points to.
Note, also, that any string whose length isn't named in the declaration is a pointer unless you're running in the compatibility mode that makes "string" into "string[255]"--this mode exists only for compatibility with very old code that was written when this was the only strings we had.
Since you appear to be simply writing the whole thing out there's no reason to be playing games with fixed size records. Simply write each field to a stream, write the length of a string before writing the string itself so you can load it back in properly. The file will be smaller and nothing gets truncated.
Also, as he says, use tFileStream. The old format has it's uses for a file of records that is left on disk, there's no reason to use it in a case like this.