using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using Microsoft.Win32; namespace XFEToolBox.QuickTools; public sealed partial class QuickToolPage { private void BuildQr() { var input = Field("QrInput", Context.Text ?? "", true); input.Height = 220; var result = Field("QrResult", "", true, true); result.MinHeight = 90; result.Height = 100; var image = new Image { Height = 290, Stretch = Stretch.Uniform, Margin = new Thickness(16) }; BitmapSource? current = null; var empty = Stack(Label("二维码预览", 22), Hint("输入文字或链接后生成\n也可拖入已有二维码图片")); empty.HorizontalAlignment = HorizontalAlignment.Center; empty.VerticalAlignment = VerticalAlignment.Center; var stage = new Grid { Height = 320, Background = Brushes.White }; stage.Children.Add(image); stage.Children.Add(empty); void Show(BitmapSource bitmap) { current = bitmap; image.Source = bitmap; empty.Visibility = Visibility.Collapsed; } async Task Decode(string path) { var bitmap = await Task.Run(() => QrService.Load(path), cancellation.Token); Show(bitmap); Result(await Task.Run(() => QrService.Decode(bitmap), cancellation.Token), result); } var modes = new TabControl(); modes.Items.Add(new TabItem { Header = "生成", Content = Stack(Hint("文字 / 网址"), input, Primary("生成二维码", async () => { string value = input.Text; Show(await Task.Run(() => QrService.Encode(value), cancellation.Token)); Result(value, result); }), Hint("支持中文 · 内容仅在本地编码")) }); modes.Items.Add(new TabItem { Header = "识别", Content = Stack(Label("从图片读取内容", 19), Hint("拖入图片到右侧预览区,或选择本地图片。识别出来的网址不会自动打开。"), Primary("识别图片", async () => { string? path = ChooseFile("图片|*.png;*.jpg;*.jpeg;*.bmp;*.gif;*.webp|所有文件|*.*"); if (path is not null) await Decode(path); }), ActionButton("识别剪贴板图片", async () => { var bitmap = Clipboard.GetImage() ?? throw new InvalidOperationException("剪贴板中没有图片。"); bitmap.Freeze(); Show(bitmap); Result(await Task.Run(() => QrService.Decode(bitmap), cancellation.Token), result); })) }); var right = Section("二维码", stage, Actions(ActionButton("复制图片", () => { if (current is null) throw new InvalidOperationException("请先生成或读取图片。"); Clipboard.SetImage(current); status.Text = "已复制二维码图片。"; }), ActionButton("保存 PNG", () => { if (current is null) throw new InvalidOperationException("没有可保存的图片。"); var dialog = new SaveFileDialog { Filter = "PNG 图片|*.png", FileName = "二维码.png", OverwritePrompt = false }; if (dialog.ShowDialog(Window.GetWindow(this)) == true) { QrService.Save(current, dialog.FileName); status.Text = "已保存:" + dialog.FileName; } }))); DropFiles(right, paths => { string? path = paths.FirstOrDefault(File.Exists); if (path is not null) _ = Run(() => Decode(path)); }); body.Children.Add(Split(Card(modes), right, 1, 1.2)); body.Children.Add(Section("二维码内容", result, Copy(result))); } }