using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Controls.Primitives; using System.Text.RegularExpressions; namespace CSRender { public partial class MainWindow : Window { //コンボボックスの要素 public class ComboBoxSet { public int Id { get; set; } public string Item { get; set; } } //クリックしたときに全体を選択 private void PageBox_GotFocusSelectAll(object sender, RoutedEventArgs e) { TextBox box = (TextBox)sender; //box.SelectAll(); this.Dispatcher.InvokeAsync(() => { Task.Delay(10); box.SelectAll(); }); } //ページ指定のプルダウンに応じてテキストボックスを活性化/非活性化 private void PageRange_SelectionChanged(object sender, SelectionChangedEventArgs e) { var SelectedItem = (ComboBoxSet)PageRange.SelectedItem; if (SelectedItem == null) return; string PageType = (string)SelectedItem.Item; if (PageType == "指定") { pageBox.IsEnabled = true; pageLabel.IsEnabled = true; } else { pageBox.IsEnabled = false; pageLabel.IsEnabled = false; } } //数字とハイフン、カンマ以外を無効化 private void PageBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { var Pagebox = (TextBox)sender; string str = Pagebox.Text;//文字列 var inputPage = e.Text;//入力された文字 //正規表現で入力文字の判定、数字とピリオド、カンマならtrue bool PageCheck = new System.Text.RegularExpressions.Regex("[0-9,-]").IsMatch(inputPage); //入力文字が数値とカンマ、ハイフン以外だったら無効 if (PageCheck == false) { e.Handled = true;//無効 return;//終了 } //キャレット(カーソル)位置が先頭(0)であるときの、ハイフン入力は無効 if (Pagebox.CaretIndex == 0 && inputPage == "-") { e.Handled = true; return; } //キャレット(カーソル)位置が先頭(0)であるときの、カンマ入力は無効 if (Pagebox.CaretIndex == 0 && inputPage == ",") { e.Handled = true; return; } } //誤ったハイフン・カンマ、数字の入力を修正 private void PageBox_LostFocus(object sender, RoutedEventArgs e) { //ハイフン、カンマの削除 var PageBox = (TextBox)sender; string inputText = PageBox.Text; // -,や,- は入力ミスなので後の文字だけ削除 inputText = inputText.Replace("-,", "-"); inputText = inputText.Replace(",-", ","); //先頭か末尾にあった場合は削除 if (inputText.StartsWith(",") || inputText.EndsWith(",")) { inputText = inputText.TrimStart(','); inputText = inputText.TrimEnd(','); } if (inputText.StartsWith("-") || inputText.EndsWith("-")) { inputText = inputText.TrimStart('-'); inputText = inputText.TrimEnd('-'); } //先頭が0の場合は1に修正 if (inputText.StartsWith("0")) { inputText = inputText.TrimStart('0'); inputText = "1" + inputText; } PageBox.Text = inputText; } private void PageBox_PreviewExecuted(object sender, ExecutedRoutedEventArgs e) { //貼り付け無効 if (e.Command == ApplicationCommands.Paste) { e.Handled = true; } } //スペースキーが押されたときは、それを無効にする private void PageBox_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space) e.Handled = true; } } }