A
A
artem782014-10-13 01:01:43
Perl
artem78, 2014-10-13 01:01:43

Perl + Win32::GUI - How to override default event handler behavior?

I am using the Win32::GUI library. I want to make a filter for the TextField - if the user enters something incorrectly, ignore the character input. I tried return -1 - the program closes, it does not react to other return values. In fact, we need an analogue of preventdefault from javascript.

use Win32::GUI();

$w = Win32::GUI::Window->new(
  -size => [300, 200],
);

$w->AddTextfield(
  -name => 'tf',
  -pos => [10, 10],
  -size => [100, 20]
);

sub tf_Update {
  if ($w->tf->Text() !~ m/^([0-9]{0,8}(?:[\.,][0-9]{0,2})?)$/) {
    # preventdefault
    # игнорируем ввод
  }
}

$w->Center();
$w->Show();

Win32::GUI::Dialog();

sub w_Terminate {
    return -1;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
gangabass, 2014-10-23
@gangabass

sub tf_Update {

    if ( $w->tf->Text() !~ m/^([0-9]{0,8}(?:[\.,][0-9]{0,2})?)$/ ) {

        $w->tf->Text("");
    }
}

This code clears the field completely . If you need to delete only the last entered character, then you can cut it off from the current value of the field...

U
UraBogort, 2015-11-11
@UraBogort

use Win32::GUI();

$w = Win32::GUI::Window->new(
  -size => [300, 200],
);

$w->AddTextfield(
  -name => 'tf',
  -pos => [10, 10],
  -size => [100, 20],
  -text => '',
);

$w->Center();
$w->Show();

Win32::GUI::Dialog();

sub w_Terminate {
    return -1;
}
sub tf_Update {

  my $buf = $w->tf->Text();
  $buf=~s/(\s|\d)//;                        #фильтруем цифры буквы
  $w->tf->Text($buf);
  #$w->tf->SetSel(length($buf),length($buf));
  $w->tf->SetSel( $buf=length($buf), $buf); #как установить курсор а конец красивее? Я незнаю!
  
  return 1;
  
}
__END__
#или так
sub tf_Update {

    my @gs  = $w->tf->GetSel();
    my $buf = $w->tf->Text();
    if ( $buf =~ s/(\s|\d)// ) {
        $w->tf->Text($buf);
        if ( $gs[0] > 0 ) {
            $w->tf->SetSel( $gs[0] - 1, $gs[0] - 1 );
        }
    }

    return 1;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question