program XMLPath_Control_Procedure_andMore;
//olevariant by max #sign:Max: MAXBOX10: 22/10/2019 22:55:14
//http://www.rosettacode.org/wiki/XML/XPath#Delphi
//https://www.freepascal.org/~michael/articles/openoffice1/openoffice.pdf
//task: open an XML Document and write nodes
Const
IXML =
'' +
' ' +
' - ' +
' Invisibility Cream' +
' 14.50' +
' Makes you invisible' +
'
' +
' - ' +
' Levitation Salve' +
' 23.99' +
' Levitate yourself for upto 3 hours per application'+
'
' +
' ' +
' ' +
' - ' +
' Blork and Freen Instameal' +
' 4.95' +
' A tasty meal in a tablet; just add water' +
'
' +
' - ' +
' Grob winglets' +
' 3.56' +
' Tender winglets of Grob. Just add water' +
'
' +
' ' +
'';
var d, freq: double;
count_inside, count, i: integer;
objServiceManager, objDesktop, objDocument: OleVariant;
openargs: variant;
FHaveDocument: boolean;
vararr: array[1..3] of variant;
const
Size = 25;
Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
// http://www.rosettacode.org/wiki/Formatted_numeric_output#Delphi
fVal = 7.125;
Procedure FormattedNumericOutput;
begin
Writeln(FormatFloat('0000#.000',fVal));
Writeln(FormatFloat('0000#.0000000',fVal));
Writeln(FormatFloat('##.0000000',fVal));
Writeln(FormatFloat('0',fVal));
Writeln(FormatFloat('#.#E-0',fVal));
Writeln(FormatFloat('#,##0.00;;Zero',fVal));
//Readln;
end;
function DecodeBase58(const Input: string): TByteArray;
var
C: Char;
I, J: Integer;
begin
SetLength(Result, Size);
//for C in Input do begin
for I:= 1 to length(Input) do begin
if Input[I] = C then
I := Pos(C, Alphabet) - 1;
if I = -1 then
raise; //
Exception.CreateFmt('Invalid character found: %s', [C]);
for J := High(Result) downto 0 do begin
I := I + (58 * Result[J]);
Result[J] := I mod 256;
I := I div 256;
end;
if I <> 0 then
raise;
Exception.Create('Address too long');
end;
end;
// Solve A x = b
procedure gaussTT (A, b, x : TMatrix);
var rowx : integer;
i, j, k, n, m : integer;
amax, xfac, temp, temp1 : double;
begin
rowx := 0; // Keep count of the row interchanges
//n := A.r;
for k := 1 to n - 1 do begin
//amax := abs (A[k,k]);
m := k;
// Find the row with largest pivot
for i := k + 1 to n do begin
//xfac := abs (A[i,k]);
if xfac > amax then
begin
amax := xfac;
m := i;
end;
end;
if m <> k then begin // Row interchanges
rowx := rowx+1;
//temp1 := b[k,1];
//b[k,1] := b[m,1];
//b[m,1] := temp1;
for j := k to n do begin
//temp := a[k,j];
//a[k,j] := a[m,j];
//a[m,j] := temp;
end;
end;
for i := k+1 to n do begin
//xfac := a[i, k]/a[k, k];
for j := k+1 to n do
//a[i,j] := a[i,j]-xfac*a[k,j];
//b[i,1] := b[i,1] - xfac*b[k,1]
end;
end;
// Back substitution
for j := 1 to n do begin
k := n-j + 1;
//x[k,1] := b[k,1];
for i := k+1 to n do begin
//x[k,1] := x[k,1] - a[k,i]*x[i,1];
end;
//x[k,1] := x[k,1]/a[k,k];
end;
end;
procedure TOfficeWriterDriver_OpenDocument(FN: String);
var OpenParams, SaveParams, wProperties: Variant;
objServiceManager, objDesktop, objDocument: OleVariant;
objText, objCursor: Variant;
rS: string;
begin
objServiceManager:= CreateOleObject('com.sun.star.ServiceManager')
objDesktop:= objServiceManager.createInstance('com.sun.star.frame.Desktop')
OpenParams:= VarArrayCreate([0, -1], varVariant);
If (fn<>'') then FN:='file:///'+StringReplace(FN,'\','/',[rfReplaceAll])
else FN:='private:factory/swriter';
objDocument:= objDesktop.LoadComponentFromURL(FN,'_default',0,OpenParams);
If (VarIsEmpty(objDocument) or VarIsNull(objDocument)) then
Raise ;
//EWordDriver.Create(’Could not open document’);
//'Inserting some Text
//'Create a text object
objText:= objDocument.getText;
//'Create a cursor object
objCursor:= objText.createTextCursor;
rS:= #13;
objText.insertString(objCursor, 'maXbox4 at OpenOffice created text ',false)
FHaveDocument:=True;
end;
// Return a Variant array of 12 random numbers.
function RandomDozen: Variant;
var
I: Integer; key: char;
begin
Result := VarArrayCreate([1, 12], varDouble);
//for I := VarArrayLowBound(Result) to VarArrayHighBound(Result) do
//Result[I] := Random;
//for I := 1 to 12 do
//Result[I] := RandomF;
if wIsCharAlpha(Key) then Key := #0;
if CharIsAlpha(Key) then Key := #0;
end;
procedure TForm1Findwindow_Remote_Notepad;
var
wnd: HWND; i: Integer; s: string;
begin
wnd := FindWindow('notepad', '');
if wnd <> 0 then begin
wnd := FindWindowEx(wnd, 0, 'Edit', '');
// Write Text in Notepad.
s := 'Hello maXPad 4 ecotronics'+#13#10+'second line:';
for i := 1 to Length(s) do
SendMessage(wnd, WM_CHAR, Ord(s[i]), 0);
// Simulate Return Key.
PostMessage(wnd, WM_KEYDOWN, VK_RETURN, 0);
// Simulate Space.
PostMessage(wnd, WM_KEYDOWN, VK_SPACE, 0);
SendMessage(wnd, WM_CHAR, 5, 0);
//send time of F5 command in notepad!
PostMessage(wnd, WM_KEYDOWN, VK_F5, 0);
end;
end;
procedure RemoteControlClick(Sender: TObject) ;
var
targetWnd: HWND;
begin
// Simulate PRINTSCREEN - snapshot of the full screen
//PostKeyEx32(VK_SNAPSHOT, [], False) ;
// Simulate PRINTSCREEN - snapshot of the active window
PostKeyEx32(VK_SNAPSHOT, [ssAlt], False) ;
//%windir%\system32\mspaint.exe
if cyShellExecute('open','mspaint','','',1) <> 0 then begin
sleep(1500)
//PostKeyEx32(VK_CONTROL, [], False);
//PostKeyEx(W, Ord('V'), [ssCtrl], False); {paste from keyboard}
PostKeyEx32(Ord('V'), [ssCtrl], False);
//and prepare to save
PostKeyEx32(Ord('S'), [ssCtrl], False);
//and save prompt
PostKeyEx32(Ord('S'), [ssAlt], False);
targetWnd:= FindWindow('mspaint', '')
writeln('win test handle : '+itoa(targetWnd))
end;
// Simulate Spacebar key
//PostKeyEx32(VK_space, [], False) ; //( I changed this)
// Simulate Alt+F4 - close active window
//PostKeyEx32(VK_F4, [ssAlt], False) ;
end;
function distanceEM(x1,x2,y1,y2 :Integer) : Double;
begin
result := sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); ///Euclidian
// result := abs(x1 - x2) + abs(y1 - y2); // Manhattan
// result := power(power(abs(x1 - x2), p) + power(abs(y1 - y2), p), (1 / p)); // Minkovski
end;
//http://www.rosettacode.org/wiki/Primality_by_trial_division#Pascal
function primeD(n: integer): boolean;
var
i: integer; max: real;
begin
if n = 2 then
result := true
else if (n <= 1) or (n mod 2 = 0) then
result := false
else begin
result := true; i := 3; max := sqrt(n);
while i <= max do begin
if n mod i = 0 then begin
result := false; exit
end;
i := i + 2
end
end
end;
function IsPrimeDE(aNumber: Integer): Boolean;
var
I: Integer;
begin
Result:= True;
if(aNumber = 2) then Exit;
Result:= not ((aNumber mod 2 = 0) or
(aNumber <= 1));
if not Result then Exit;
for I:=3 to Trunc(Sqrt(aNumber)) do
if(aNumber mod I = 0) then begin
Result:= False;
Break;
end;
end;
function IsPrimeDE2(const x: integer): Boolean;
var
i: integer;
begin
i := 2;
repeat
if X mod i = 0 then begin
Result := False;
Exit;
end;
Inc(i);
until i > Sqrt(x);
Result := True;
end;
procedure GetXMLFromURLMentor(apath: string);
var
xml: Olevariant; //IXMLDOMDocument;
node, nodedet: Olevariant;
nodes_row, nodes_se, itemnode: olevariant;
i, j: Integer;
URL: string;
begin
//url := 'https://www.w3schools.com/xml/note.xml';
//URL:= 'https://www.w3schools.com/xml/cd_catalog.xml';
xml:= CreateOleObject('Microsoft.XMLDOM') as IXMLDocument;
xml.async := False;
xml.resolveExternals:= false;
xml.validateOnParse:= false;
if xml.loadXML(apath) then writeln('xml load success'); // or use loadXML to load XML document using a supplied string
if xml.parseError.errorCode <> 0 then
writeln('XML Load error:' + xml.parseError.reason);
Writeln('First item node:');
itemnode := xml.selectNodes('//item');
Writeln(itemnode.item[0].text);
Writeln('');
//nodes_row := xml.SelectNodes('/doc/data/row');
nodes_row:= xml.SelectNodes('//price');
writeln('total price nodes: '+itoa(nodes_row.length))
for i:= 0 to nodes_row.length - 1 do begin
//node:= nodes_row.item[i];
writeln(itoa(i)+':price='+nodes_row.item[i].text);
end;
// nodes_se:= node.selectNodes('catalog/search_engine/se_url');
writeln('')
nodes_se:= xml.selectNodes('//item/name');
writeln('total item names: '+itoa(nodes_se.length))
for j:= 0 to nodes_se.length - 1 do begin
//node:= nodes_se.item[j];
writeln('Item name = ' + nodes_se.item[j].text);
end;//}
//Memo1.Lines.Add('--------------');
writeln('------------------------');
//end; //}
xml:= unassigned;
xml:= NULL;
end;
//http://www.rosettacode.org/wiki/Dot_product#Delphi
type
doublearray = array of Double;
function DotProduct(const A, B : doublearray): Double;
var
I: integer;
begin
assert (Length(A) = Length(B), 'Input arrays must be the same length');
Result := 0;
for I := 0 to Length(A) - 1 do
Result := Result + (A[I] * B[I]);
end;
procedure getDotProduct;
var
x,y: doublearray;
begin
SetLength(x, 3);
SetLength(y, 3);
x[0] := 1; x[1] := 3; x[2] := -5;
y[0] := 4; y[1] :=-2; y[2] := -1;
WriteLn(floattoStr(DotProduct(x,y)));
PrintF('%.18f',[DotProduct(x,y)])
//ReadLn;
end;
//https://delphisource.blogspot.com/2007/10/virtual-key-codes.html
var n: integer;
begin //@main rain
//function CreateOleObject(const ClassName: String): IDispatch;
//objServiceManager:= CreateOleObject('com.sun.star.ServiceManager')
//objDesktop:= objServiceManager.createInstance('com.sun.star.frame.Desktop')
//TOfficeWriterDriver_OpenDocument('')
//Exit will cause the calling procedure to continue with the statement after the point at which the procedure was called.
//RemoteControlClick(self);
//TForm1Findwindow_Remote_Notepad;
{if ShellExecute3('notepad.exe','',seCmdopen) = '' then begin
//writeln(ShellExecute3('notepad.exe','',seCmdopen))
writeln('Multiprocessing Notepad Runs on CPU 1');
sleep(1100)
TForm1Findwindow_Remote_Notepad;
end; }
GetXMLFromURLMentor(IXML);
writeln(GETDOSOutput('cmd.exe /c wmic cpu get name','C:\'));
writeln('after remote key control main proc call')
// TOfficeWriterDriverOpenDocument('C:\maxbook\maxboxpython\ML2020\Beurteilung_Semesterarbeit_FS19_PML2_Oggenfuss.ods')
for n := 0 to 50 do
if (primeD(n)) then
write(itoa(n)+ ' ');
writeln('second Prime Time'+CRLF)
for n := 0 to 50 do
if (ISprimeDE(n)) then
write(itoa(n)+ ' ');
//FormattedNumericOutput;
getDotProduct;
End.
Ref: First item node:
-
Invisibility Cream
14.50
Makes you invisible
Price = 14.50
Price = 23.99
Price = 4.95
Price = 3.56
Item name = Invisibility Cream
Item name = Levitation Salve
Item name = Blork and Freen Instameal
Item name = Grob winglets
https://www.freepascal.org/~michael/articles/openoffice1/openoffice.pdf
procedure TForm1.SpeedButton2Click(Sender: TObject);
var
W: HWnd;
begin
W := Memo1.Handle;
PostKeyEx(W, VK_END, [ssCtrl, ssShift], False); {select all}
PostKeyEx(W, Ord('C'), [ssCtrl], False); {copy to clipboard}
PostKeyEx(W, Ord('C'), [ssShift], False); {replace with C}
PostKeyEx(W, VK_RETURN, [], False); {new line}
PostKeyEx(W, VK_END, [], False); {go to end}
PostKeyEx(W, Ord('V'), [ssCtrl], False); {paste from keyboard}
end;
procedure PostKeyExHWND(hWindow: HWnd; key: Word; const shift: TShiftState;
specialkey: Boolean);
{************************************************************
* Procedure PostKeyEx
*
* Parameters:
* hWindow: target window to be send the keystroke
* key : virtual keycode of the key to send. For printable
* keys this is simply the ANSI code (Ord(character)).
* shift : state of the modifier keys. This is a set, so you
* can set several of these keys (shift, control, alt,
* mouse buttons) in tandem. The TShiftState type is
* declared in the Classes Unit.
* specialkey: normally this should be False. Set it to True to
* specify a key on the numeric keypad, for example.
* If this parameter is true, bit 24 of the lparam for
* the posted WM_KEY* messages will be set.
* Description:
* This procedure sets up Windows key state array to correctly
* reflect the requested pattern of modifier keys and then posts
* a WM_KEYDOWN/WM_KEYUP message pair to the target window. Then
* Application.ProcessMessages is called to process the messages
* before the keyboard state is restored.
* Error Conditions:
* May fail due to lack of memory for the two key state buffers.
* Will raise an exception in this case.
* NOTE:
* Setting the keyboard state will not work across applications
* running in different memory spaces on Win32 unless AttachThreadInput
* is used to connect to the target thread first.
*Created: 02/21/96 16:39:00 by P. Below
************************************************************}
type
TBuffers = array [0..1] of TKeyboardState;
var
pKeyBuffers: ^TBuffers;
lParam: LongInt;
begin
(* check if the target window exists *)
if IsWindow(hWindow) then
begin
(* set local variables to default values *)
pKeyBuffers := nil;
lParam := MakeLong(0, MapVirtualKey(key, 0));
(* modify lparam if special key requested *)
if specialkey then
lParam := lParam or $1000000;
(* allocate space for the key state buffers *)
New(pKeyBuffers);
try
(* Fill buffer 1 with current state so we can later restore it.
Null out buffer 0 to get a "no key pressed" state. *)
GetKeyboardState(pKeyBuffers^[1]);
FillChar(pKeyBuffers^[0], SizeOf(TKeyboardState), 0);
(* set the requested modifier keys to "down" state in the buffer*)
if ssShift in shift then
pKeyBuffers^[0][VK_SHIFT] := $80;
if ssAlt in shift then
begin
(* Alt needs special treatment since a bit in lparam needs also be set *)
pKeyBuffers^[0][VK_MENU] := $80;
lParam := lParam or $20000000;
end;
if ssCtrl in shift then
pKeyBuffers^[0][VK_CONTROL] := $80;
if ssLeft in shift then
pKeyBuffers^[0][VK_LBUTTON] := $80;
if ssRight in shift then
pKeyBuffers^[0][VK_RBUTTON] := $80;
if ssMiddle in shift then
pKeyBuffers^[0][VK_MBUTTON] := $80;
(* make out new key state array the active key state map *)
SetKeyboardState(pKeyBuffers^[0]);
(* post the key messages *)
if ssAlt in Shift then
begin
PostMessage(hWindow, WM_SYSKEYDOWN, key, lParam);
PostMessage(hWindow, WM_SYSKEYUP, key, lParam or $C0000000);
end
else
begin
PostMessage(hWindow, WM_KEYDOWN, key, lParam);
PostMessage(hWindow, WM_KEYUP, key, lParam or $C0000000);
end;
(* process the messages *)
Application.ProcessMessages;
(* restore the old key state map *)
SetKeyboardState(pKeyBuffers^[1]);
finally
(* free the memory for the key state buffers *)
if pKeyBuffers <> nil then
Dispose(pKeyBuffers);
end; { If }
end;
end; { PostKeyEx }
// Beispiel:
procedure TForm1.Button1Click(Sender: TObject);
var
targetWnd: HWND;
begin
targetWnd := FindWindow('notepad', nil)
if targetWnd <> 0 then
begin
PostKeyExHWND(targetWnd, Ord('I'), [ssAlt], False);
end;
end;
To give you an impression on how Automation works with OOo, here is a quick example:
'The service manager is always the starting point
'If there is no office running then an office is started up
Set objServiceManager= WScript.CreateObject("com.sun.star.ServiceManager")
'Create the Desktop
Set objDesktop= objServiceManager.createInstance("com.sun.star.frame.Desktop")
'Open a new empty writer document
Dim args()
Set objDocument= objDesktop.loadComponentFromURL("private:factory/swriter",_
"_blank", 0, args)
'Create a text object
Set objText= objDocument.getText
'Create a cursor object
Set objCursor= objText.createTextCursor
'Inserting some Text
objText.insertString objCursor, "The first line in the newly created text document."&_
vbLf, false
fDocument.StoreToURL('file:///'+ StringReplace(FileName, '\', '/', [rfIgnoreCase, rfReplaceAll]), wProperties);
Exception: [automation bridge] : [automation bridge] unexpected exception in UnoConversionUtilities::variantToAny !.
time profiler
1000000:
mX4 executed: 14/10/2019 21:19:08 Runtime: 0:0:23.528 Memload: 43% use
ProcessMessagesOFF:
mX4 executed: 14/10/2019 21:21:54 Runtime: 0:0:4.734 Memload: 43% use
IFPS
byte code execud: 14/10/2019 21:26:21 Runtime: 0:0:2.898 Memload: 43% use
mX4 executed: 22/10/2019 22:16:30 Runtime: 0:0:2.250 Memload: 37% use
----code_cleared_checked_clean----