use Win32::GUI;
use Win32::API;
use warnings;
use strict;

# Our MAIN window on the desktop.
my $mainwindow = new Win32::GUI::Window(
	-name => "mainwindow",
	-pos => [100, 100],
	-size => [200,200],
	-text => "Scrolling subwindow demo",
	-onResize => \&mainresize
);

# Our window with horizontal scrollbar inside the main window
my $scrollwindow = new Win32::GUI::Window (
	-parent => $mainwindow,
	-name => "scrollwindow",
	-pos => [20,20],
	-size => [$mainwindow->ScaleWidth - 40,$mainwindow->ScaleHeight - 40],
	-popstyle => WS_CAPTION | WS_SIZEBOX,	# Remove caption and sizing handles
	-pushstyle => WS_CHILD,
	-hscroll => 1,
	-onScroll => \&scrolled
);

# Our scrollable area inside the window with scrollbars
my $scrollarea = new Win32::GUI::Window (
	-parent => $scrollwindow,
	-name => "scrollarea",
	-pos => [0,0],
	-size => [400,$scrollwindow->ScaleHeight],
	-popstyle => WS_CAPTION | WS_SIZEBOX,
	-pushstyle => WS_CHILD
);

my $SETPARENT = new Win32::API("user32","SetParent","NN","N") or die "Failed to load SetParent from user32.dll";
# put scrollarea into scrollwindow:
$SETPARENT->Call($scrollarea->{-handle},$scrollwindow->{-handle});
# put scrollwindow into mainwindow:
$SETPARENT->Call($scrollwindow->{-handle},$mainwindow->{-handle});


# Define some scrolling parameters
$scrollwindow->ScrollRange(0,0,$scrollarea->ScaleWidth);
$scrollwindow->ScrollPage(0,$scrollwindow->ScaleWidth);

# Add some buttons:
for(0..4) {
	$scrollarea->AddButton(
		-name => "Button".$_,
		-pos => [$_ * 100,0],
		-size => [100,$scrollwindow->ScaleHeight],
		-text => "Button $_",
	);
}

$mainwindow->Show();
$scrollwindow->Show();
$scrollarea->Show();
Win32::GUI::Dialog;

sub scrolled {
	# scrolling handler.
	my($obj, $scrollbar, $operation, $position) = @_;

	# Move the scrollbar and set the left edge of the scrollarea at the same time:
	my $realpos = $scrollwindow->Scroll($scrollbar, $operation, $position);

	# If we're dragging the thumb we want a live update:
	if($operation == SB_THUMBTRACK) { $realpos = $position };
	$scrollarea->Left(0 - $realpos);
}

sub mainresize {
	$scrollwindow->Width($mainwindow->ScaleWidth - 40);
	$scrollwindow->Height($mainwindow->ScaleHeight - 40);

	$scrollarea->Height($scrollwindow->ScaleHeight);

	$scrollwindow->ScrollRange(0,0,$scrollarea->ScaleWidth);
	$scrollwindow->ScrollPage(0,$scrollwindow->ScaleWidth);

	for(0..4) {
		$scrollarea->{"Button$_"}->Height($scrollarea->ScaleHeight);
	}
}