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 { /// /// WinCloseButton.xaml 的交互逻辑 /// 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; } } }