1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- 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.Interop;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Shapes;
- namespace Test.WindowsMessage
- {
- /// <summary>
- /// WinCloseButton.xaml 的交互逻辑
- /// </summary>
- public partial class WinCloseButton : Window
- {
- //捕获是调用close的关闭,还是关闭按钮的关闭
- public WinCloseButton()
- {
- InitializeComponent();
- this.SourceInitialized += new EventHandler(win_SourceInitialized);
- }
- private void win_SourceInitialized(object sender, EventArgs e)
- {
- win_SourceInitialized1(sender, e);
- }
- //第一种
- void win_SourceInitialized1(object sender, EventArgs e)
- {
- IntPtr handle = (new WindowInteropHelper(this)).EnsureHandle();
- HwndSource.FromHwnd(handle).AddHook(new HwndSourceHook(WndProc));
- }
- //第二种
- void win_SourceInitialized2(object sender, EventArgs e)
- {
- HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
- if (hwndSource != null)
- {
- hwndSource.AddHook(new HwndSourceHook(WndProc));
- }
- }
- private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
- {
- const int WM_SYSCOMMAND = 0x0112;
- const int SC_CLOSE = 0xF060;
- if (msg == WM_SYSCOMMAND && (int)wParam == SC_CLOSE)
- {
- Application.Current.Shutdown();
- }
- return IntPtr.Zero;
- }
- }
- }
|