ContextDialog.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Drawing;
  3. using System.Windows.Forms;
  4. namespace BeatLyrics.Tool.Dialogs
  5. {
  6. internal class ContextDialog
  7. {
  8. public static void PopTextBox(Point screenPoint, string orig, Action<DialogResult, string> ret)
  9. {
  10. var form = new Form
  11. {
  12. FormBorderStyle = FormBorderStyle.None,
  13. StartPosition = FormStartPosition.Manual,
  14. Location = screenPoint,
  15. ShowInTaskbar = false,
  16. };
  17. var textBox = new TextBox
  18. {
  19. Left = 0,
  20. Top = 0,
  21. };
  22. form.Controls.Add(textBox);
  23. var closed = false;
  24. textBox.PreviewKeyDown += delegate (object sender, PreviewKeyDownEventArgs args)
  25. {
  26. if (closed) return;
  27. if (args.KeyCode == Keys.Escape)
  28. {
  29. form.DialogResult = DialogResult.Cancel;
  30. form.Close();
  31. }
  32. if (args.KeyCode == Keys.Enter)
  33. {
  34. form.DialogResult = DialogResult.OK;
  35. form.Close();
  36. }
  37. };
  38. textBox.LostFocus += delegate
  39. {
  40. if (closed) return;
  41. form.DialogResult = DialogResult.OK;
  42. form.Close();
  43. };
  44. form.FormClosed += delegate { closed = true; ret(form.DialogResult, textBox.Text); };
  45. form.Show();
  46. form.Height = textBox.Height;
  47. textBox.Text = orig;
  48. textBox.SelectAll();
  49. var tw = TextRenderer.MeasureText(orig, textBox.Font).Width;
  50. if (tw > textBox.Width) textBox.Width = tw;
  51. form.Width = textBox.Width;
  52. }
  53. }
  54. }