TScrollBox scroll in runtime using buttons and mouse - delphi

Hi guys after 3 days of not finding the right answer i come to you for help :) , so my question is this i have a TScrollBox component in my form and i create TImage components at FormCreate event this fills up the Scroll-box with components but when i want to scroll through them using Scroll-by it goes way beyond the end of the last component, the code will run on 2 buttons and mouse wheel 1 button left 2 button right and mouse wheel either sides
procedure TForm1.RightButtonClick(Sender: TObject);
var
Coff : Double;
begin
Coff := 6.6;
scrollbarpos := scrollbarpos - 100;
if((scrollbarpos>= -Coff * screen.PixelsPerInch) AND (scrollbarpos<=0)) then
begin
ScrollBox1.ScrollBy(-100,0);
end
else
begin
scrollbarpos := scrollbarpos + 100;
if(scrollbarpos < -(Coff /2) * screen.PixelsPerInch) then
begin
ScrollBox1.ScrollBy(-Round(scrollbarpos+Coff *screen.PixelsPerInch),0);
scrollbarpos := round( -Coff * screen.PixelsPerInch);
end;
end;
end;
this code works but when i change my "Control Panel\Appearance and Personalization\Display" settings from smaller - 100% to medium or large it goes beyond the last component, it has something to do with the Coff value. Any ideas of a more effective way to scroll without using scroll bars because they are invisible.
Project can be found here: http://www.failai.lt/i9famvv1my9f/proj.rar.htm

Related

Form opens in a random position in Delphi

I wanted to make that form would open in a random position on a screen.
I found the similar question here https://stackoverflow.com/a/51314375/19160533
But i didnt get how to implement this.
Im using Delphi 11.
Thanks!
You can set the top and left of the form on FormShow:
procedure TForm1.FormShow(Sender: TObject);
begin
self.Top := Random(1000);
left := Random(2000);
end;
for a better result, you can calculate the desktop dimensions and subtract the form width and height.

How to temporarily stop a control from being painted?

We have a win control object which moves its clients to some other coordiantes. The problem is, when there are too many children - for example 500 controls - the code is really slow.
It must be because of each control being repainted each time I set Left and Top property. So, I want to tell the WinControl object stop being repainted, and after moving all objects to their new positions, it may be painted again (Something like BeginUpdate for memo and list objects). How can I do this?
Here's the code of moving the objects; it's quite simple:
for I := 0 to Length(Objects) - 1 do begin
with Objects[I].Client do begin
Left := Left + DX;
Top := Top + DY;
end;
end;
As Cosmin Prund explains, the cause for the long duration is not an effect of repainting but of VCL's realignment requisites at control movement. (If it really should take as long as it does, then you might even need to request immediate repaints).
To temporarily prevent realignment and all checks and work for anchors, align settings and Z-order, use DisableAlign and EnableAlign. And halve the count of calls to SetBounds by called it directly:
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
Control: TControl;
begin
for I := 0 to 499 do
begin
Control := TButton.Create(Self);
Control.SetBounds((I mod 10) * 40, (I div 10) * 20, 40, 20);
Control.Parent := Panel1;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
C: TControl;
begin
// Disable Panel1 paint
SendMessage(Panel1.Handle, WM_SETREDRAW, Integer(False), 0);
Panel1.DisableAlign;
try
for I := 0 to Panel1.ControlCount - 1 do
begin
C := Panel1.Controls[I];
C.SetBounds(C.Left + 10, C.Top + 5, C.Width, C.Height);
end;
finally
Panel1.EnableAlign;
// Enable Panel1 paint
SendMessage(Panel1.Handle, WM_SETREDRAW, Integer(True), 0);
// Update client area
RedrawWindow(Panel1.Handle, nil, 0, RDW_INVALIDATE or RDW_UPDATENOW or RDW_ALLCHILDREN);
end;
end;
Your assumption that the slowness comes from re-painting controls is probably true, but not the whole story. The default Delphi code that handles moving controls would delay painting until the next WM_PAINT message is received, and that would happen when the message queue is pumped, after you complete moving all the controls. Unfortunately there are a lot of things involved in this, that default behavior can be altered in many places, including Delphi and Windows itself. I've used the following code to test what happens when you move a control at runtime:
var i: Integer;
begin
for i:=1 to 100 do
begin
Panel1.Left := Panel1.Left + 1;
Sleep(10); // Simulate slow code.
end;
end;
The behaviour depends on the control! A TControl (example: TLabel) is going to behave according to Delphi's rules, but a TWinControl depends on too many factors. A simple TPanel is not repainted until after the loop, in the case of TButton on my machine only the background is re-painted, while a TCheckBox is fully repainted. On David's machine the TButton is also fully repainted, proving this depends on many factors. In the case of TButton the most likely factor is the Windows version: I tested on Windows 8, David tested on Windows 7.
AlignControl Avalanche
Anyhow, there's an other really important factor to be taken into account. When you move a control at runtime, all the rules for alignment and anchoring for all the controls need to be taken into account. This likely causes an avalanche of AlignControls / AlignControl / UpdateAnchorRules calls. Since all those calls end up requiring recursive invocations of the same, the number of calls will be exponential (hence your observation that moving lots of objects on a TWinControl is slow).
The simplest solution is, as David suggests, placing everything on a Panel and moving the panel as one. If that's not possible, and all your controls are actually TWinControl (ie: they have a Window Handle), you could use:
BeginDeferWindowPos, DeferWindowPos, EndDeferWindowPos
I would put all the controls in a panel, and then move the panel rather than the controls. That way you perform the shift in a one single operation.
If you would rather move the controls within their container then you can use TWinControl.ScrollBy.
For what it is worth, it is more efficient to use SetBounds than to modify Left and Top in separate lines of code.
SetBounds(Left+DX, Top+DY, Width, Height);
To speed up you should set the Visible property of you WinControl to False during child movement to avoid repainting.
Together with SetBounds you will get the best from moving the child controls.
procedure TForm1.MoveControls( AWinControl : TWinControl; ADX, ADY : Integer );
var
LIdx : Integer;
begin
AWinControl.Visible := False;
try
for LIdx := 0 to Pred( AWinControl.ControlCount ) do
with AWinControl.Controls[LIdx] do
begin
SetBounds( Left + ADX, Top + ADY, Width, Height );
end;
finally
AWinControl.Visible := True;
end;
end;
BTW As David suggested, moving the parent is much faster than each child.

Trying to make an Editbox move up and down with a button click

hi i'm trying to make an editbox move down from 300 by 30 when a button is clicked, and upon clicking the same button again, make editbox move back up by 30 to its original position. However when i click the button ive made it just moves up by 30 each time, where am i going wrong? here is my code,
procedure TfrmProject.Button3Click(Sender: TObject);
begin
if Edit1.Top = 300 then
Edit1.Top := Edit1.Top + 30 else
Edit1.Top := Edit1.Top - 30;
end;
EDIT: I have realised that due to my form being long and having a vertical scrollbar, the property Top of the editbox changes in response to where i am on the form, i.e if i'm at the top of my form the Top property of the edit box increases (the editbox is near the bottom of the form), therefore my new question is how could i ensure the editbox only moves between 2 fixed points, as following the recent suggestions the edit box moves between two points with a 30 distance between them, but their positions on the form change.
This works perfectly fine for me.
Create a new Delphi VCL Forms Application
Drop a TEdit and a TButton on the new form. Set the Top' property of each to50using theObject Inspector`.
Double-click Button1, and paste the following code to replace the newly generated TForm1.Button1Click event:
procedure TForm1.Button1Click(Sender: TObject);
begin
if Edit1.Top = 50 then
Edit1.Top := Edit1.Top + 30
else
Edit1.Top := 50;
end;
Run the application. Repeatedly clicking Button1 makes Edit1 move up and down from 50 to 80.
This means your comparison is wrong. Set the Button1.Top explicitly to the original coordinate (300 in your code) instead of reducing by 30.
Then the original setting of the Top property was not 300. Or the movement is not (fully) allowed due to constraint, align or anchor settings of the edit control or those of adjacent controls.
Possible solutions:
When Top should always be 300:
Set Edit1.Top to 300. And make sure there is movement possible.
When 299 < Top < 330:
Change the comparison to:
if Edit1.Top < 330 then
When Top should remain undesided:
Use the Tag property of the edit control (or a private variable, or...) to remember in which direction it has to move:
procedure TForm1.Button1Click(Sender: TObject);
const
MoveNorth = 0;
MoveSouth = 1;
begin
if Edit1.Tag = MoveNorth then
Edit1.Top := Edit1.Top + 30 else
Edit1.Top := Edit1.Top - 30;
if Edit1.Tag = MoveNorth then
Edit1.Tag := MoveSouth else
Edit1.Tag := MoveNorth;
end;
Use Ken's solution.
Here's a little trick for you.
Place a label with no caption on the form with the Top property set to 0 and the anchors set to [akLeft, akTop]. Use that label as a place holder, so you always know where the top of the form is. When it's off the screen at the top from scrolling, the Top property will actually become negative.
Now, use the label's Top property as your starting point, so to put the edit box at 300 pixels from the top:
Edit1.Top := Label1.Top + 300;
That's the easy way. I figure the proper way is to use the position of the vertical scroll bar like this:
Edit1.Top := 300 - Self.VertScrollBar.Position;

How to make a panel appear when the mouse moves over it? delphi

How can I make a panel appear with everything that is in it when I move my mouse over its location?
When I move it off again, it fades back out?
Doing it when it is visible is not a problem (except the fading out), I can do this with onmouseleaves.
But when it is invisible how do you make it visible?
thankssss
Put the panel on another (blank) panel. Make the "magic" panel show up when you get mouse movement over the blank panel.
Edited, because I now learned the OP has the Panel over a WebBrowser. My solution of placing an dummy / blank panel no longer works; Interfering with mouse messages going to the WebBrowser is also not a good idea, so here's a simple way to fix this. I'm using an TTimer with it's interval set to "100" and I'm pooling the mouse coordinates.
procedure TForm25.Timer1Timer(Sender: TObject);
var PR: TRect; // Panel Rect (in screen coordinates)
CP: TPoint; // Cursor Position (always in screen coordinates)
begin
// Get the panel's coordinates and convert them to Screen coordinates.
PR.TopLeft := Panel1.ClientToScreen(Panel1.ClientRect.TopLeft);
PR.BottomRight := Panel1.ClientToScreen(Panel1.ClientRect.BottomRight);
// Get the mouse cursor position
CP := Mouse.CursorPos;
// Is the cursor over the panel?
if (CP.X >= PR.Left) and (CP.X <= PR.Right) and (CP.Y >= PR.Top) and (CP.Y <= PR.Bottom) then
begin
// Panel should be made visible
Panel1.Visible := True;
end
else
begin
// Panel should be hidden
Panel1.Visible := False;
end;
end;
If you have an area that your panel will appear in, you can capture the mouse move event for the underlying form or parent panel and check it is within the bounds that your invisible panel will appear in.
eg. (pseudocode)
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if ((X > MyPanel.Left) and (Y > MyPanel.Top) and (X < mypanel.right) and
(Y < mypanel.bottom)) then
begin
mypanel.visible := true;
end;
end;

How can Virtual Treeview control be made to always scroll by lines?

The Virtual Treeview scrolls vertically by pixels, unlike the way the standard Delphi grids, TListView and TTreeView (or most of the other such controls that I am aware of) scroll by line and keep a full line visible at the top of the control at all times. When I use the cursor keys to navigate, then depending on direction either the first or the last line is completely visible. When scrolling with the mouse there is no alignment whatsoever.
This behaviour can be observed for example with the Structure window in Delphi 2007 and 2009.
Is there any way to set the many properties to have the behaviour of the standard windows controls? Or is there a set of patches somewhere to achieve this?
This is what I came up with the help of Argalatyr, looks like it does what I want it to:
procedure TForm1.FormCreate(Sender: TObject);
begin
VirtualStringTree1.ScrollBarOptions.VerticalIncrement :=
VirtualStringTree1.DefaultNodeHeight;
end;
procedure TForm1.VirtualStringTree1Resize(Sender: TObject);
var
DY: integer;
begin
with VirtualStringTree1 do begin
DY := VirtualStringTree1.DefaultNodeHeight;
BottomSpace := ClientHeight mod DY;
VirtualStringTree1.OffsetY := Round(VirtualStringTree1.OffsetY / DY) * DY;
end;
end;
procedure TForm1.VirtualStringTree1Scroll(Sender: TBaseVirtualTree; DeltaX,
DeltaY: Integer);
var
DY: integer;
begin
if DeltaY <> 0 then begin
DY := VirtualStringTree1.DefaultNodeHeight;
VirtualStringTree1.OffsetY := Round(VirtualStringTree1.OffsetY / DY) * DY;
end;
end;
You could intercept the TBaseVirtualTree.OnScroll event and use the virtual treeview's canvas's return value for textheight('M') as the amount to change TBaseVirtualTree.offsety in order to increment (scroll up) or decrement (scroll down). Could also test to ensure that pre-scroll position modulus textheight('M') is zero (to avoid scrolling by the right amount from the wrong position).
Alternatively, this post on the Virtual Treeview forum suggests another approach: hide the virtual treeview's native scroll bars with VCL scroll bars and then do the scrolling yourself (trapping VCL scroll events and programmatically scrolling the virtual treeview).

Resources