WinCloseButton.xaml.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Interop;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using System.Windows.Shapes;
  15. namespace Test.WindowsMessage
  16. {
  17. /// <summary>
  18. /// WinCloseButton.xaml 的交互逻辑
  19. /// </summary>
  20. public partial class WinCloseButton : Window
  21. {
  22. //捕获是调用close的关闭,还是关闭按钮的关闭
  23. public WinCloseButton()
  24. {
  25. InitializeComponent();
  26. this.SourceInitialized += new EventHandler(win_SourceInitialized);
  27. }
  28. private void win_SourceInitialized(object sender, EventArgs e)
  29. {
  30. win_SourceInitialized1(sender, e);
  31. }
  32. //第一种
  33. void win_SourceInitialized1(object sender, EventArgs e)
  34. {
  35. IntPtr handle = (new WindowInteropHelper(this)).EnsureHandle();
  36. HwndSource.FromHwnd(handle).AddHook(new HwndSourceHook(WndProc));
  37. }
  38. //第二种
  39. void win_SourceInitialized2(object sender, EventArgs e)
  40. {
  41. HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
  42. if (hwndSource != null)
  43. {
  44. hwndSource.AddHook(new HwndSourceHook(WndProc));
  45. }
  46. }
  47. private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  48. {
  49. const int WM_SYSCOMMAND = 0x0112;
  50. const int SC_CLOSE = 0xF060;
  51. if (msg == WM_SYSCOMMAND && (int)wParam == SC_CLOSE)
  52. {
  53. Application.Current.Shutdown();
  54. }
  55. return IntPtr.Zero;
  56. }
  57. }
  58. }