I use windows UI Automation framework to access controls in other processes. I catch the system SETFOCUS messages and check the type of the focused control if it is an edit control or not. This sometimes works perfectly, but sometimes I won't get the focused control from setfocus message but only a handle to an upper control in the tree, for example a handle to a pane. What am I doing wrong?
I tried to find out which child element of the pane currently got keyboard focus by checking the UIA_HasKeyboardFocusPropertyId of the enabled child elements, but all of them will return false.
Below is the code which checks the keyboard focus property.
Additionally, for some reason I am not able to use the Automation Element Property Identifiers. They should be listed here: https://msdn.microsoft.com/en-us/library/windows/desktop/ee684017(v=vs.85).aspx
I got the values from archive.org, because the content is no longer available.
In the code, "i" is the type of the currenty focused control which got the windows setfocus message.
if (i = 50033) then // 50033 (pane)
begin
uiAuto.CreatePropertyCondition(30010, true, cond); // 30010 (enabled property)
if cond <> nil then
begin
focusedElement.FindAll(TreeScope_Children, cond, children);
if children <> nil then
begin
children.Get_Length(length);
if length > 0 then
begin
Memo1.Lines.Add('length: ' + IntToStr(length));
for j := 0 to length-1 do
begin
children.GetElement(j, tempChildElement);
tempChildElement.Get_CurrentControlType(k);
Memo1.Lines.Add('child element type: ' + IntToStr(k));
tempChildElement.GetCurrentPropertyValue(30008, keybFocusBool); // 30008 (UIA_HasKeyboardFocusPropertyId)
if keybFocusBool then
Memo1.Lines.Add('child has keyboard focus: TRUE');
keybFocusbool := false;
end;
end;
end;
end;
end;
Related
I have made an application in Delphi that handles some defined system wide hotkeys, works perfectly. However, for some hotkey functionality I have to trigger/simulate some keyboard strokes such as ALT+ENTER. This works great when the user releases the hotkey keys directly, but when the keys are still pressed by the user the keyboard simulation fail.
Is there a way (with windows API) to check if all keys are released before I process a keyboard simulation?
Use GetAsyncKeyState as this API reflects the true current state of the keyboard, and not when your app last called GetMessage. Just write a loop that calls it for each value between 0 and 0xFF.
If the most significant bit is set, the key is down
Thanks go to #David Ching and #David Heffernan (two Davids!) The solution is not only to test keyboard input but also mouse input or better, the state of input devices.
The mouse is also included because of:
{ Virtual Keys, Standard Set }
VK_LBUTTON = 1;
VK_RBUTTON = 2;
VK_MBUTTON = 4; { NOT contiguous with L & RBUTTON }
So, if don't want to test mousebuttons you have to exclude it from the loop. It's better to check these also because there are hotkeys that must be used with the mouse. It's better to check everything on input is idle.
function isUserInputDevicesInUse() : Boolean; // Keyboard pressed / mouse pressed?
var
i : LongInt;
begin
i:=256;
Result:=FALSE;
while( i > 0 ) and ( NOT Result ) do
begin
Dec( i );
Result:=( GetAsyncKeyState(i) < 0 );
end;
end;
function isUserInputDevicesIdle() : Boolean;
begin
Result:=NOT isUserInputDevicesInUse();
end;
I'm building multiplatform( iOS, Android, OSX, Windows APP) in Firemonkey. One of the things I'm trying to do is create a custom listbox item( with more data elements) that will work on all these platforms:
will give you ability to select item(s), display properly.
According to research I did, probably the best way for this is to create custom style for list box item and define data elements there. That's what I did.
I'm creating items from client dataset in this procedure:
procedure TMasterDetailForm.LoadAvailable;
var i: Integer;
Item: TListBoxItem;
begin
lstAvailable.Clear;
//Add Header
lstAvailable.BeginUpdate;
Item := TListBoxItem.Create( lstAvailable );
Item.Parent := lstAvailable;
Item.Height := 70;
//Item.OnApplyStyleLookup := ListItemApplyStyleLookupHandler;
Item.StyleLookup := AvailableListHeaderStyle;
//Add Details
cdsAvailable.First;
for I := 1 to cdsAvailable.RecordCount do
begin
Item := TListBoxItem.Create( lstAvailable );
Item.Parent := lstAvailable;
Item.Height := 50;
//Item.Selectable := True;
//Item.OnApplyStyleLookup := ListItemApplyStyleLookupHandler;
Item.StyleLookup := AvailableListItemStyle;
//Item.StyleLookup := 'ListboxItem1Style1';
Item.StylesData[ txtWoNum ] := cdsAvailable.FieldByName( 'work package' ).AsString;
Item.StylesData[ txtAircraft ] := cdsAvailable.FieldByName('aircraft').AsString;
Item.StylesData[ txtTaskDescription ] := cdsAvailable.FieldByName('task').AsString;
cdsAvailable.Next;
end;
lstAvailable.EndUpdate;
end;
Everything gets styled properly on all platforms, except that tapping(clicking) on ListBoxItem on Android or iOS, doesn't highlight the ListBoxItem. If I unissign style then selecting items also works.I can't figure out how to fix this.
Btw, onclick event on ListBox seems to work properly( itemindex changes).
Any input will be greatly appreciated.
Edit( 12/12/2014) : I tried simplifying the example by adding items manually in the ListBox editor and discarding this code here, and I found out that animation for selecting the listbox item changes. So, I customized the listbox item and only changed TextColor to blue. In runtime on Android when you select the listbox item it just changes the color of the text to black instead of painting the whole row. Any ideas how to have listbox behave in similar way like when there is no style attached to it?
Sorry my english is bad.
I have a solution (tested in XE7):
Open a form
Change the IDE Style to "iOS"
Select the TListBox an open a context menu and select "Edit Default
Style": the StyleBook2 is created.
Add a TRectangle component in the style "listboxstyle/background"
with the name "selection". This is the magic!
Now, Firemonkey found the 'selection' component and work fine!
If you already have StyleBook2 component before these steps, you may need to delete it, be careful!
I would like to detect when the form is going to be maximized to save certain settings (not related to the size nor position) and modify the size and position a little bit. Is there an universal way to do it ?
I've tried to catch the WM_SYSCOMMAND message like in this article. It works well for maximization from menu, by maximize button, but it's not fired when I press the WIN + UP keystroke. Does anyone know an universal way how to catch the maximization event including the case with WIN + UP keystroke ?
Thanks
You can use the WM_GETMINMAXINFO message to save the state of the window and then use the WMSize message to check if the window was maximized.
in you form declare the mesage handler like so :
procedure WMSize(var Msg: TMessage); message WM_SIZE;
And handle like this :
procedure TForm57.WMSize(var Msg: TMessage);
begin
if Msg.WParam = SIZE_MAXIMIZED then
ShowMessage('Maximized');
end;
WIN+UP does not generate WM_SYSCOMMAND messages, that is why you cannot catch them. It does generate WM_GETMINMAXINFO, WM_WINDOWPOSCHANGING, WM_NCCALCSIZE, WM_MOVE, WM_SIZE, and WM_WINDOWPOSCHANGED messages, though. Like RRUZ said, use WM_GETMINMAXINFO to detect when a maximize operation is about to begin and WM_SIZE to detect when it is finished.
IMO, You cannot use WM_GETMINMAXINFO to "detect when a maximize operation is about to begin" as #Remy stated.
In-fact the only message that can is WM_SYSCOMMAND with Msg.CmdType=SC_MAXIMIZE or undocumented SC_MAXIMIZE2 = $F032 - but it's not being sent via Win+UP, or by using ShowWindow(Handle, SW_MAXIMIZE) for example.
The only way I could detect that a window is about to be maximized is via WM_WINDOWPOSCHANGING which is fired right after WM_GETMINMAXINFO:
type
TForm1 = class(TForm)
private
procedure WMWindowPosChanging(var Message: TWMWindowPosChanging); message WM_WINDOWPOSCHANGING;
end;
implementation
const
SWP_STATECHANGED = $8000;
procedure TForm1.WMWindowPosChanging(var Message: TWMWindowPosChanging);
begin
inherited;
if (Message.WindowPos^.flags and (SWP_STATECHANGED or SWP_FRAMECHANGED)) <> 0 then
begin
if (Message.WindowPos^.x < 0) and (Message.WindowPos^.y < 0) then
ShowMessage('Window state is about to change to MAXIMIZED');
end;
end;
So, here is the discussion I have just read:
http://www.mail-archive.com/delphi#delphi.org.nz/msg02315.html
BeginUpdate and EndUpdate is not thi procedures I need ...
Overriding API Call? I tried to get Update procedures code from ComCtrls unit, nut did not found...
Maybe you could post here a code to fix thi flicker of statusbar compoent if the only text changes in it? I mean - something like TextUpdate or some kind of TCanvas method or PanelsRepaint ... ?
The flickering is caused by this code:
Repeat
BlockRead(Fp, BuffArrayDebug[LineIndex], DataCapac, TestByteBuff); // DataCapac = SizeOf(DWORD)
ProgressBar1.StepIt;
if RAWFastMode.Checked then begin // checks for fast mode and modifyies progressbar
if BuffArrayDebug[LineIndex] = 0 then begin ProgressBar2.Max := FileSize(Fp) - DataCapac; ProgressBar2.Position := (LineIndex + 1) * DataCapac; LineDecr := True; end;
end else begin ProgressBar2.Max := FileSize(Fp); ProgressBar2.Position := LineIndex * DataCapac end;
if PreviewOpn.Caption = '<' then begin // starts data copying to preview area if expanded
Memo1.Lines.BeginUpdate;
if (LineIndex mod DataCapac) > 0 then HexMerge := HexMerge + ByteToHex(BuffArrayDebug[LineIndex]) else
begin
Memo1.Lines.Add(HexMerge); HexMerge := '';
end;
Memo1.Lines.EndUpdate;
end;
StatusBar1.Panels[0].Text := 'Line: ' + Format('%.7d',[LineIndex]) + ' | Data: ' + Format('%.3d',[BuffArrayDebug[LineIndex]]) + ' | Time: ' + TimeToStr(Time - TimeVarStart); StatusBar1.Update;
if FindCMDLineSwitch(ParamStr(1)) then begin
TrayIcon.BalloonTitle := 'Processing ' + ExtractFileName(RAWOpenDialog.FileName) + ' and reading ...';
TrayIcon.BalloonHint := 'Current Line: ' + inttostr(LineIndex) + #10#13 + ' Byte Data: ' + inttostr(TestByteBuff) + #10#13 + ' Hex Data: ' + ByteToHex(TestByteBuff);
TrayIcon.ShowBalloonHint;
end;
Inc(LineIndex);
Until EOF(Fp);
Any ideas?
There was comment with this link ( http://www.stevetrefethen.com/blog/UsingTheWSEXCOMPOSITEWindowStyleToEliminateFlickerOnWindowsXP.aspx ) and there is procedure that works ( no flickering whastsoever ), BUT IT IS VVVVVVVEEEEEERRRRRRYYYYYY SLOW!
1 type
2 TMyForm = class(TForm)
3 protected
4 procedure CreateParams(var Params: TCreateParams); override;
5 end;
6
7 ...
8
9 procedure TMyForm.CreateParams(var Params: TCreateParams);
10 begin
11 inherited;
12 // This only works on Windows XP and above
13 if CheckWin32Version(5, 1) then
14 Params.ExStyle := Params.ExStyle or WS_EX_COMPOSITED;
15 end;
16
Also - the target is not the form, but the StatusBar ... how to assign this method to statusbar?
The most important advise I can give you is to limit the number of status bar updates to maybe 10 or 20 per seconds. More will just cause unnecessary flicker, without any benefit for the user - they can't process the information that fast anyway.
OK, with that out of the way: If you want to use the WS_EX_COMPOSITED extended style for the status bar you have basically three options:
Create a descendent class that overrides the CreateParams() method and either install this into your IDE or (if you don't want to have it as its own component in the IDE) create the status bar at runtime.
Create a descendent class with the same name TStatusBar in another unit, override the CreateParams() method, and add this unit after ComCtrls to the form units using status bar controls. This will create an instance of your own TStatusBar class instead of the one in ComCtrls. See this answer for another example of the technique, hopefully its clear enough.
Use the vanilla TStatusBar class and set the WS_EX_COMPOSITED extended style at runtime.
I prefer the third option as the easiest one to experiment with, so here's the sample code:
procedure TForm1.FormCreate(Sender: TObject);
var
SBHandle: HWND;
begin
// This only works on Windows XP and above
if CheckWin32Version(5, 1) then begin
// NOTE: the following call will create all necessary window handles
SBHandle := StatusBar1.Handle;
SetWindowLong(SBHandle, GWL_EXSTYLE,
GetWindowLong(SBHandle, GWL_EXSTYLE) or WS_EX_COMPOSITED);
end;
end;
Edit:
If you want your code to properly support recent Windows versions and visual styles you should not even think of handling WM_ERASEBKGND yourself - the usual technique involves an empty handler for that method, and drawing the background in the WM_PAINT handler. This doesn't really work for standard controls like TStatusBar, as the background has to be drawn somewhere. If you just skip the background drawing in the WM_ERASEBKGND handler you will need to use owner-drawn panels spanning all of the status bar, otherwise the background simply won't be drawn, and the window underneath will shine through. Besides, the code for the owner-drawn panel would probably be very complex.
Again, a much better course of action would be to untangle the mess in your posted code, properly separate worker from display code, and reduce the update speed of your status bar texts to something reasonable. There just isn't any sense at all in going past the number of monitor updates per second, and even this is sensible only for games and similar visualizations.
You should check whether setting the TWinControl.DoubleBuffered property to True of the TStatusBar component will make it work. Also you can try enabling this property to the status bar's parent component (probably TForm). It's a blind shot - don't have access to the compiler from here. Another thought is to override the WM_ERASEBKGND message without calling inherited. First example found after using google: here.
----- Update after author's comment
I finally got access to the compiler and now it's working. We can use the WS_EX_COMPOSITED solution. All you need is is to create your own custom component basing on TCustomStatusBar or just create a class wrapper and create your status bar instance in runtime. Like this:
TMyStatusBar = class( TCustomStatusBar )
protected
{ Flickering work-around }
procedure CreateParams( var Params : TCreateParams ) ; override ;
end ;
TForm1 = class( TForm )
// (...)
private
FStatusBar : TMyStatusBar ;
// (...)
end ;
-------------
procedure TMyStatusBar.CreateParams( var Params : TCreateParams ) ;
begin
inherited ;
if CheckWin32Version( 5,1 ) then
Params.ExStyle := Params.ExStyle or WS_EX_COMPOSITED ;
end ;
-------------
{ Creating component in runtime }
procedure TForm1.FormCreate( Sender : TObject ) ;
begin
FStatusBar := TMyStatusBar.Create( Self ) ;
FStatusBar.Parent := Self ;
FStatusBar.Panels.Add ;
end ;
And it works for me. Good luck!
Is there a way to get/set the location of the scrollbar in Internet Explorer/Firefox?
I am not looking to do that from inside the HTML/ASP/Javascript code, but from an application outside the browser (using WinAPI for example), and without using BHO.
From the search I've done right now it seems impossible, so I'm dropping a question here as a last try.
For Internet Explorer, you can use COM automation to enumerate all active Internet Explorer windows/tabs and then access the DOM tree of the document displayed in the window/tab to access and read the scroll position.
The following sample code uses Delphi as a programming language. The mechanism would be similar in C++, VB or C#
var
ShWindows: ShellWindows;
InetExplorer: InternetExplorer;
Count: Integer;
I: Integer;
HTMLDocument: IHTMLDocument2;
Elem: IHTMLElement2;
ScrollPosY: Integer;
begin
// Create ShellWindows Object
SHWindows:= CoShellWindows.Create;
// Number of explorer windows/tabs (win explorer and ie)
Count:= ShWindows.Count;
ShowMessage(Format('There are %d explorer windows open.', [Count]));
// For all windows/tabs
for I:= 0 to (Count - 1) do
begin
// Get as InetExplorer interface
InetExplorer:= SHWindows.item(I) as InternetExplorer;
// Check to see if this explorer window contains a web document
if Supports(InetExplorer.Document, IHTMLDocument2, HTMLDocument) then
begin
// Get body Element
Elem:= HTMLDocument.body as IHTMLElement2;
// Read vertical scroll position
ScrollPosY:= Elem.scrollTop;
// If this is 0 so far, maybe there is a scroll position in root element
if ScrollPosY = 0 then
begin
Elem:= HTMLDocument.body.parentElement as IHTMLElement2;
ScrollPosY:= Elem.scrollTop;
end;
// Display
ShowMessage(IntToStr(Elem.scrollTop));
end;
end;
end;
For documentation, start here: http://msdn.microsoft.com/en-us/library/bb773974(VS.85).aspx