截获WndProc过程

为防止点击窗体右上角的关闭按钮(X按钮)关闭窗体,我们可以覆盖WndProc过程,只要发现消息为WM_SYSCOMMAND且wparam参数为SC_CLOSE就不让继续传下去。

Delphi代码:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs;

type
  TForm1 = class(TForm)
  private
    { Private declarations }
    procedure WndProc(var AMessage:TMessage);override;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.WndProc(var AMessage: TMessage);
begin
  if (AMessage.Msg=WM_SYSCOMMAND) and (AMessage.WParam=SC_CLOSE) then
    Exit
  else
    inherited;

end;

end.

C#代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        const int WM_SYSCOMMAND = 0x0112;
        const int SC_CLOSE = 0xF060;
        public Form1()
        {
            InitializeComponent();
        }
        protected override void WndProc(ref Message m)
        {
            if ((m.Msg == WM_SYSCOMMAND) && ((int)m.WParam == SC_CLOSE))
                return;
            base.WndProc(ref m);
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

posted on 2012-11-28 16:55  天上星  阅读(264)  评论(0编辑  收藏  举报

导航