Search Results

Search found 20 results on 1 pages for 'widestring'.

Page 1/1 | 1 

  • Delphi: Fast(er) widestring concatenation

    - by Ian Boyd
    i have a function who's job is to convert an ADO Recordset into html: class function RecordsetToHtml(const rs: _Recordset): WideString; And the guts of the function involves a lot of wide string concatenation: while not rs.EOF do begin Result := Result+CRLF+ '<TR>'; for i := 0 to rs.Fields.Count-1 do Result := Result+'<TD>'+VarAsString(rs.Fields[i].Value)+'</TD>'; Result := Result+'</TR>'; rs.MoveNext; end; With a few thousand results, the function takes, what any user would feel, is too long to run. The Delphi Sampling Profiler shows that 99.3% of the time is spent in widestring concatenation (@WStrCatN and @WstrCat). Can anyone think of a way to improve widestring concatenation? i don't think Delphi 5 has any kind of string builder. And Format doesn't support Unicode. And to make sure nobody tries to weasel out: pretend you are implementing the interface: IRecordsetToHtml = interface(IUnknown) function RecordsetToHtml(const rs: _Recordset): WideString; end; Update One I thought of using an IXMLDOMDocument, to build up the HTML as xml. But then i realized that the final HTML would be xhtml and not html - a subtle, but important, difference. Update Two Microsoft knowledge base article: How To Improve String Concatenation Performance

    Read the article

  • Delphi 2010 Wide functions vs. String functions

    - by Mick
    We're currently converting a Delphi 2007 project to Delphi 2010. We were already using Unicode (via WideStrings and TNT Unicode Controls). I was expecting to replace all Wide functions, e.g. WideUpperCase, with their equivalent, e.g. UpperCase, but they do not work the same way. For example, WideUpperCase works differently from UpperCase. WideUpperCase correctly uppercases Campañas, but UpperCase leaves the ñ in lower case. Are there any other differences that I should be aware of? e.g. do WideFormat and Format work the same? Thanks

    Read the article

  • trouble with boost::filesystem::wrecursive_directory_iterator

    - by Dogmatixed
    I'm trying to write a program to help me manage my iTunes library, including removing duplicates and cataloging certain things. At this point I'm still just trying to get it to walk through all the folders, and have run into a problem: I have a small amount of Japanese music, where the artist and/or album is written in Japanese characters. Because of how iTunes arranges things in its library the directories contain these characters. "shouldn't be a problem, though." I thought, because the boost::filesystem library has a wide character version of its recursive iterator. but when I actually try to use it, it seems to completely stop when it hits the first Japanese char. complete stop as in it doesn't finish printing the line, no carriage return or anything. now, I'm still pretty new to programming, so I'm assuming it's my mistake, anyone know why this is happening? here's what I think is the relevant code: fs::wrecursive_directory_iterator end_it; int i; try { for(fs::wrecursive_directory_iterator rec_it(full_path); rec_it != end_it; ++rec_it) { for(i = 0; i < rec_it.level(); i++) { out << "\t"; } out << rec_it->string() << std::endl; } } catch(std::exception e) { out << "something went wrong: " << e.what(); } and from my output file, minus some of the path: /Test Libs/Combine /Test Libs/Lib1 /Test Libs/Lib1/02 Too Long.m4a /Test Libs/Lib1/03 Like a Hitman, Like a Dancer.mp3 /Test Libs/Lib1/A Certain Ratio /Test Libs/Lib1/A Certain Ratio/Beyond Punk! /Test Libs/Lib1/A Certain Ratio/Unknown Album /Test Libs/Lib1/A Certain Ratio/Unknown Album/Do The Du.mp3 /Test Libs/Lib1/A Certain Ratio/Unknown Album/Shack Up.mp3 /Test Libs/Lib1/ finally, what I expect: /Test Libs/Combine /Test Libs/Lib1 /Test Libs/Lib1/02 Too Long.m4a /Test Libs/Lib1/03 Like a Hitman, Like a Dancer.mp3 /Test Libs/Lib1/A Certain Ratio /Test Libs/Lib1/A Certain Ratio/Beyond Punk! /Test Libs/Lib1/A Certain Ratio/Unknown Album /Test Libs/Lib1/A Certain Ratio/Unknown Album/Do The Du.mp3 /Test Libs/Lib1/A Certain Ratio/Unknown Album/Shack Up.mp3 /Test Libs/Lib1/??? /Test Libs/Lib1/Bring it on /Test Libs/Lib1/04 Bring it on.mp3 any thoughts? Thanks.

    Read the article

  • C++ template function specialization using TCHAR on Visual Studio 2005

    - by Eli
    I'm writing a logging class that uses a templatized operator<< function. I'm specializing the template function on wide-character string so that I can do some wide-to-narrow translation before writing the log message. I can't get TCHAR to work properly - it doesn't use the specialization. Ideas? Here's the pertinent code: // Log.h header class Log { public: template <typename T> Log& operator<<( const T& x ); template <typename T> Log& operator<<( const T* x ); template <typename T> Log& operator<<( const T*& x ); ... } template <typename T> Log& Log::operator<<( const T& input ) { printf("ref"); } template <typename T> Log& Log::operator<<( const T* input ) { printf("ptr"); } template <> Log& Log::operator<<( const std::wstring& input ); template <> Log& Log::operator<<( const wchar_t* input ); And the source file // Log.cpp template <> Log& Log::operator<<( const std::wstring& input ) { printf("wstring ref"); } template <> Log& Log::operator<<( const wchar_t* input ) { printf("wchar_t ptr"); } template <> Log& Log::operator<<( const TCHAR*& input ) { printf("tchar ptr ref"); } Now, I use the following test program to exercise these functions // main.cpp - test program int main() { Log log; log << "test 1"; log << L"test 2"; std::string test3( "test3" ); log << test3; std::wstring test4( L"test4" ); log << test4; TCHAR* test5 = L"test5"; log << test4; } Running the above tests reveals the following: // Test results ptr wchar_t ptr ref wstring ref ref Unfortunately, that's not quite right. I'd really like the last one to be "TCHAR", so that I can convert it. According to Visual Studio's debugger, the when I step in to the function being called in test 5, the type is wchar_t*& - but it's not calling the appropriate specialization. Ideas? I'm not sure if it's pertinent or not, but this is on a Windows CE 5.0 device.

    Read the article

  • 2-byte (UCS-2) wide strings under GCC

    - by Seva Alekseyev
    Hi all, when porting my Visual C++ project to GCC, I found out that the wchar_t datatype is 4-byte UTF-32 by default. I could override that with a compiler option, but then the whole wcs* (wcslen, wcscmp, etc.) part of RTL is rendered unusable, since it assumes 4-byte wide strings. For now, I've reimplemented 5-6 of these functions from scratch and #defined my implementations in. But is there a more elegant option - say, a build of GCC RTL with 2-byte wchar-t quietly sitting somewhere, waiting to be linked? The specific flavors of GCC I'm after are Xcode on Mac OS X, Cygwin, and the one that comes with Debian Linux Etch.

    Read the article

  • When and why can sprintf fail?

    - by Srekel
    I'm using swprintf to build a string into a buffer (using a loop among other things). const int MaxStringLengthPerCharacter = 10 + 1; wchar_t* pTmp = pBuffer; for ( size_t i = 0; i < nNumPlayers ; ++i) { const int nPlayerId = GetPlayer(i); const int nWritten = swprintf(pTmp, MaxStringLengthPerCharacter, TEXT("%d,"), nPlayerId); assert(nWritten >= 0 ); pTmp += nWritten; } *pTaskPlayers = '\0'; If during testing the assert never hits, can I be sure that it will never hit in live code? That is, do I need to check if nWritten < 0 and handle that, or can I safely assume that there won't be a problem? Under which circumstances can it return -1? The documentation more or less just states "If the function fails". In one place I've read that it will fail if it can't match the arguments (i.e. the formatting string to the varargs) but that doesn't worry me. I'm also not worried about buffer overrun in this case - I know the buffer is big enough.

    Read the article

  • Storing UTF8 string in a UnicodeString

    - by Mick
    In Delphi 2007 you can store a UTF8 string in a WideString and then pass that onto a Win32 function, e.g. var UnicodeStr: WideString; UTF8Str: WideString; begin UnicodeStr:='some unicode text'; UTF8Str:=UTF8Encode(UnicodeStr); Windows.SomeFunction(PWideChar(UTF8Str), ...) end; Delphi 2007 does not interfere with the contents of UTF8Str, i.e. it is left as a UTF8 encoded string stored in a WideString. But in Delphi 2010 I'm struggling to find a way to do the same thing, i.e. store a UTF8 encoded string in a WideString without it being automatically converted from UTF8. I cannot pass a pointer to UTF8 string (or RawByteString), e.g. the following will obviously not work: var UnicodeStr: WideString; UTF8Str: UTF8String; begin UnicodeStr:='some unicode text'; UTF8Str:=UTF8Encode(UnicodeStr); Windows.SomeFunction(PWideChar(UTF8Str), ...) end; Any help appreciated. Thanks.

    Read the article

  • RegisterTypeLibForUser call doesn't seem to work - any ideas ?

    - by Mmarquee
    This is really a follow on question to a previous one, where I need to register applications, TLBs and OCXs per user, rather than into HKLM. I have written the following code - based on answers here and elsewhere, BUT the TLB is not registered - no error is thrown, just nothing happens (this code snippet comes from the Embarcadero website. procedure RegisterTypeLibrary(TypeLib: ITypeLib; const ModuleName: string); var Name: WideString; HelpPath: WideString; RegisterTypeLibForUser : function(tlib: ITypeLib; szFullPath, szHelpDir: POleStr): HResult; stdcall; res : HResult; begin Name := ModuleName; HelpPath := ExtractFilePath(ModuleName); res:=RegisterTypeLib(TypeLib, PWideChar(Name), PWideChar(HelpPath)); if res <> S_OK then begin @RegisterTypeLibForUser:=GetProcAddress(GetModuleHandle('oleaut32.dll'), 'RegisterTypeLibForUser'); if (@RegisterTypeLibForUser <> nil) then begin res:=RegisterTypeLibForUser(TypeLib, PWideChar(Name), PWideChar(HelpPath)); end; end; //MessageBox(GetForegroundWindow, PChar(IntToHex(res, 8)), nil, MB_OK); OleCheck(res); end; Anyone got any pointers as I am now lost.

    Read the article

  • UTF-8 GET using Indy 10.5.8.0 and Delphi XE2

    - by Bogdan Botezatu
    I'm writing my first Unicode application with Delphi XE2 and I've stumbled upon an issue with GET requests to an Unicode URL. Shortly put, it's a routine in a MP3 tagging application that takes a track title and an artist and queries Last.FM for the corresponding album, track no and genre. I have the following code: function GetMP3Info(artist, track: string) : TMP3Data //<---(This is a record) var TrackTitle, ArtistTitle : WideString; webquery : WideString; [....] WebQuery := UTF8Encode('http://ws.audioscrobbler.com/2.0/?method=track.getcorrection&api_key=' + apikey + '&artist=' + artist + '&track=' + track); //[processing the result in the web query, getting the correction for the artist and title] // eg: for artist := Bucovina and track := Mestecanis, the corrected values are //ArtistTitle := Bucovina; // TrackTitle := Mestecani?; //Now here is the tricky part: webquery := UTF8Encode('http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=' + apikey + '&artist=' + unescape(ArtistTitle) + '&track=' + unescape(TrackTitle)); //the unescape function replaces spaces (' ') with '+' to comply with the last.fm requests [some more processing] end; The webquery looks in a TMemo just right (http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=e5565002840xxxxxxxxxxxxxx23b98ad&artist=Bucovina&track=Mestecani?) Yet, when I try to send a GET() to the webquery using IdHTTP (with the ContentEncoding property set to 'UTF-8'), I see in Wireshark that the component is GET-ing the data to the ANSI value '/2.0/?method=track.getInfo&api_key=e5565002840xxxxxxxxxxxxxx23b98ad&artist=Bucovina&track=Mestec?ni?' Here is the full headers for the GET requests and responses: GET /2.0/?method=track.getInfo&api_key=e5565002840xxxxxxxxxxxxxx23b98ad&artist=Bucovina&track=Mestec?ni? HTTP/1.1 Content-Encoding: UTF-8 Host: ws.audioscrobbler.com Accept: text/html, */* Accept-Encoding: identity User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.23) Gecko/20110920 Firefox/3.6.23 SearchToolbar/1.22011-10-16 20:20:07 HTTP/1.0 400 Bad Request Date: Tue, 09 Oct 2012 20:46:31 GMT Server: Apache/2.2.22 (Unix) X-Web-Node: www204 Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS Access-Control-Max-Age: 86400 Cache-Control: max-age=10 Expires: Tue, 09 Oct 2012 20:46:42 GMT Content-Length: 114 Connection: close Content-Type: text/xml; charset=utf-8; <?xml version="1.0" encoding="utf-8"?> <lfm status="failed"> <error code="6"> Track not found </error> </lfm> The question that puzzles me is am I overseeing anything related to setting the property of the tidhttp control? How can I stop the well-formated URL i'm composing in the application from getting wrongfully sent to the server? Thanks.

    Read the article

  • TVirtualStringTree compatibility between Delphi 7 and Delphi 2010 - 'Parameter lists differ'

    - by Brian Frost
    Hi, I've made a form containing a TVirtualStringTree that works in Delphi 7 and Delphi 2010. I notice that as I move between the two platforms I get the message '...parameter list differ..' on the tree events and that the string type is changing bewteen TWideString (D7) and string (D2010). The only trick I've found to work to suppress this error is to use compiler directives as follows: {$IFDEF TargetDelphi7} procedure VirtualStringTree1GetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); {$ELSE} procedure VirtualStringTree1GetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); {$ENDIF} and to repeat this where the events are implemented. Am I missing a simple solution? Thanks.

    Read the article

  • Delphi Unicode String Type Stored Directly at its Address

    - by Andreas Rejbrand
    I want a string type that is Unicode and that stores the string directly at the adress of the variable, as is the case of the (Ansi-only) ShortString type. I mean, if I declare a S: ShortString and let S := 'My String', then, at @S, I will find the length of the string (as one byte, so the string cannot contain more than 255 characters) followed by the ANSI-encoded string itself. What I would like is a Unicode variant of this. That is, I want a string type such that, at @S, I will find a unsigned 32-bit integer containing the length of the string in bytes (or in characters, which is half the number of bytes) followed by the Unicode representation of the string. I have tried WideString, UnicodeString, and RawByteString, but they all appear only to store an adress at @S, and the actual string somewhere else (I guess this has do do with reference counting and such). I suspect that there is no built-in type to use, and that I have to come up with my own way of storing text the way I want (which actually is fun). Am I right?

    Read the article

  • CueText equivalent for a TMemo

    - by JosephStyons
    I have this Delphi code to set the cue text of a control on my form: procedure TfrmMain.SetCueText(edt: TWinControl; cueText: string); const ECM_FIRST = $1500; EM_SETCUEBANNER = ECM_FIRST + 1; begin SendMessage(edt.Handle,EM_SETCUEBANNER,0, LParam(PWideChar(WideString(cueText)))); end; I want the same effect on a TMemo, but the MSDN document says: You cannot set a cue banner on a multiline edit control or on a rich edit control. Is there a standard way to have a cuetext effect on a TMemo, or do I have to fiddle with the OnEnter/OnExit events and roll my own?

    Read the article

  • Exchanging strings (PChar) between a Freepascal compiled DLL and a Delphi compiled EXE

    - by John Riche
    After a lot of experimentations, I found a way to exchange PChar from a FreePascal compiled DLL with a Delphi compiled EXE. I'm in charge of both the DLL and EXE source code but one MUST BE in FreePascal and the other one in Delphi. My solution involves the following methods in the DLL: function GetAString(): PChar; var aString: string; begin aString := 'My String'; result := StrAlloc(length(aString) + 1); StrPCopy(result, aString); end; procedure FreeString(aString: PChar); begin StrDispose(aString); end; And from the Delphi EXE, to call the GetAString method, I need to Call the GetAString method, save the PChar to an actual Delphi String and call the FreeString method. Is this the best way of exchanging a string from a FreePascal DLL with a Delphi EXE ? Can I avoid the call to FreeString from Delphi ? And finally, if that's the correct solution, how will it behave with Delphi 2010 and the WideString by default: do I need to force WidePChar in FreePascal too ?

    Read the article

  • Is there any better IDOMImplementation other than MSXML?

    - by Chau Chee Yang
    There are 3 IDOMImplementation available in Delphi: MSXML Xerces XML ADOM XML v4 MSXML is the default IDOMImplementation. My test is count the time need to load a 10MB xml file. I use a Delphi unit generated from a XSD using XML data binding to load the xml file. This unit has 3 common function: function Getmenubar(Doc: IXMLDocument): IXMLMenubarType; function Loadmenubar(const FileName: WideString): IXMLMenubarType; function Newmenubar: IXMLMenubarType; I learn from the web that some comment that MSXML's overhead is high that it doesn't perform if compare to other XML parser. However, my study shows that MSXML is the best among others. Xerces XML 2nd and ADOM XML v4 the worst: MSXML - 0.6410 seconds Xerces XML - 2.4220 seconds ADOM XML v4 - 67.50 seconds I also come across with OmniXML that claim to have much better performance compare to MSXML but I never success using it with the unit generated by XML data binding. Is there any other vendor that implement IDOMImplementation of Delphi that work much better than MSXML? I am using Delphi 2010 and Windows 7.

    Read the article

  • Piloting Microsoft Word With Ole in C++ Builder : how to put Word in the foreground.

    - by Getz
    Hi! I've got a code (which works fine) for piloting word with C++ Builder. It's useful for reaching different bookmarks in the document. Variant vNom, vWDocuments, vWDocument, vMSWord, vSignets, vSignet; vNom = WideString("blabla.doc"); try { vMSWord = Variant::GetActiveObject("Word.Application"); } catch(...) { vMSWord = Variant::CreateObject("Word.Application"); } vMSWord.OlePropertySet("Visible", true); vWDocuments = vMSWord.OlePropertyGet("Documents"); vWDocument = vWDocuments.OleFunction("Open", vNom); vSignets = vWDocument.OlePropertyGet("BookMarks"); if (vSignets.OleFunction("Exists", signet)) { vSignet = vSignets.OleFunction("Item", signet); vSignet.OleFunction("Select"); } But once the document is opened, the user can no longer see when an other bookmark has been reached, since the application stays in background. Does anyone know how i can do to make Word displayed in the foreground, or to light-up the document in the taskbar? Thanks!

    Read the article

  • Resetting a PChar variable

    - by scott-thornton
    Hi, I don't know much about delphi win 32 programming, but I hope someone can answer my question. I get duplicate l_sGetUniqueIdBuffer saved into the database which I want to avoid. The l_sGetUniqueIdBuffer is actually different ( the value of l_sAuthorisationContent is xml, and I can see a different value generated by the call to getUniqueId) between rows. This problem is intermittant ( duplicates are rare...) There is only milliseconds difference between the update date between the rows. Given: ( unnesseary code cut out) l_sGetUniqueIdBuffer: PChar; FOutputBufferSize : integer; FOutputBufferSize := 1024; while( not dmAccomClaim.ADOQuClaimIdentification.Eof ) do begin // Get a unique id for the request l_sGetUniqueIdBuffer := AllocMem (FOutputBufferSize); l_returnCode := getUniqueId (m_APISessionId^, l_sGetUniqueIdBuffer, FOutputBufferSize); dmAccomClaim.ADOQuAddContent.Active := False; dmAccomClaim.ADOQuAddContent.Parameters.ParamByName('pContent').Value := (WideString(l_sAuthorisationContent)); dmAccomClaim.ADOQuAddContent.Parameters.ParamByName('pClaimId').Value := dmAccomClaim.ADOQuClaimIdentification.FieldByName('SB_CLAIM_ID').AsString; dmAccomClaim.ADOQuAddContent.Parameters.ParamByName('pUniqueId').Value := string(l_sGetUniqueIdBuffer); dmAccomClaim.ADOQuAddContent.ExecSQL; FreeMem( l_sAuthorisationContent, l_iAuthoriseContentSize ); FreeMem( l_sGetUniqueIdBuffer, FOutputBufferSize ); end; I guess i need to know, is the value in l_sGetUniqueIdBuffer being reset for every row??

    Read the article

  • Delphi Unicode String Type Stored Directly at its Address (or "Unicode ShortString")

    - by Andreas Rejbrand
    I want a string type that is Unicode and that stores the string directly at the adress of the variable, as is the case of the (Ansi-only) ShortString type. I mean, if I declare a S: ShortString and let S := 'My String', then, at @S, I will find the length of the string (as one byte, so the string cannot contain more than 255 characters) followed by the ANSI-encoded string itself. What I would like is a Unicode variant of this. That is, I want a string type such that, at @S, I will find a unsigned 32-bit integer (or a single byte would be enough, actually) containing the length of the string in bytes (or in characters, which is half the number of bytes) followed by the Unicode representation of the string. I have tried WideString, UnicodeString, and RawByteString, but they all appear only to store an adress at @S, and the actual string somewhere else (I guess this has do do with reference counting and such). Update: The most important reason for this is probably that it would be very problematic if sizeof(string) were variable. I suspect that there is no built-in type to use, and that I have to come up with my own way of storing text the way I want (which actually is fun). Am I right? Update I will, among other things, need to use these strings in packed records. I also need manually to read/write these strings to files/the heap. I could live with fixed-size strings, such as <= 128 characters, and I could redesign the problem so it will work with null-terminated strings. But PChar will not work, for sizeof(PChar) = 1 - it's merely an address. The approach I eventually settled for was to use a static array of bytes. I will post my implementation as a solution later today.

    Read the article

  • delphi app freezes whole win7 system

    - by avar
    Hello i have a simple program that sorts a text file according to length of words per line this program works without problems in my xp based old machine now i run this program on my new win7/intel core i5 machine, it freezes whole system and back normal after it finishes it's work. i'v invastigated the code and found the line causing the freeze it was this specific line... caption := IntToStr(i) + '..' + IntTostr(ii); i'v changed it to caption := IntTostr(ii); //slow rate change and there is no freeze and then i'v changed it to caption := IntTostr(i); //fast rate change and it freeze again my main complete procedure code is var tword : widestring; i,ii,li : integer; begin tntlistbox1.items.LoadFromFile('d:\new folder\ch.txt'); tntlistbox2.items.LoadFromFile('d:\new folder\uy.txt'); For ii := 15 Downto 1 Do //slow change Begin For I := 0 To TntListBox1.items.Count - 1 Do //very fast change Begin caption := IntToStr(i) + '..' + IntTostr(ii); //problemetic line tword := TntListBox1.items[i]; LI := Length(tword); If lI = ii Then Begin tntlistbox3.items.Add(Trim(tntlistbox1.Items[i])); tntlistbox4.items.Add(Trim(tntlistbox2.Items[i])); End; End; End; end; any idea why ? and how to fix it? i use delphi 2007/win32

    Read the article

  • Windows CE Programming Serial Port - Getting Garbled Output

    - by user576639
    I am programming a Windows CE 6 device (Motorola MC3100 scanner Terminal). Using Lazarus FPC to compile it. After 3 weeks work I reluctantly post here in the hope someone can suggest why I am getting garbled output from the serial port. The code I am using is posted below. This is the standard code I have found from several places. The OpenPort works OK. When I send the string using SendString('ABCDEF') I get garbled input to the PC Serial port such as: 4[#131][#26][#0][#0][#0][#0] (the bracketed data indicates that it is a non-printable character ASCII Code) Obviously it is connecting to the port OK AND it is sending the correct no of characters (7). I have tried all combinations of Baud Rate, Data Bits, Parity and Stop Bits without any joy. Also tried changing cable, on a different PC etc. Could it be I need to set something else in the DCB? Any help or suggestions would be GREATLY appreciated. unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, Windows, LResources; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Label1: TLabel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); function OpenPort(ComPort:String;BaudRate,ByteSize,Parity,StopBits:integer):String; procedure SendString(str:String); private { private declarations } public { public declarations } end; var Form1: TForm1; cc:TCOMMCONFIG; Connected:Boolean; implementation {$R *.lfm} var F: TextFile; var hComm: THandle; str: String; lrc: LongWord; { TForm1 } function OpenPort(ComPort:String;BaudRate,ByteSize,Parity,StopBits:integer):String; var cc:TCOMMCONFIG; SWide:WideString; Port:LPCWSTR; begin SWide:=ComPort; Port:=PWideChar(SWide); result:=''; if (1=1) then begin Connected:=False; hComm:=CreateFile(Port, GENERIC_READ or GENERIC_WRITE,0, nil,OPEN_EXISTING,0,0); if (hComm = INVALID_HANDLE_VALUE) then begin ShowMessage('Fail to Open'); exit; end; GetCommState(hComm,cc.dcb); cc.dcb.BaudRate:=BaudRate; cc.dcb.ByteSize:=ByteSize; cc.dcb.Parity:=Parity; cc.dcb.StopBits:=StopBits; if not SetCommState(hComm, cc.dcb) then begin result:='SetCommState Error!'; CloseHandle(hComm); exit; end; Connected:=True; end; end; procedure TForm1.Button1Click(Sender: TObject); begin OpenPort('COM1:',9600,8,0,0); end; procedure TForm1.Button2Click(Sender: TObject); begin SendString('ABCDEFG'); end; procedure TForm1.SendString(str:String); var lrc:LongWord; begin if (hComm=0) then exit; try if not PurgeComm(hComm, PURGE_TXABORT or PURGE_TXCLEAR) then raise Exception.Create('Unable to purge com: '); except Exit; end; WriteFile(hComm,str,Length(str), lrc, nil); end; end.

    Read the article

1