自言自语

I'm Wang Xianyuan, writing for myself, more studying, more experience…

Disable Form右上的 “X”

By

要Disable Form "X" –> Close的功能(变暗灰色),事实上便是从Form左上方的System
Menu将关闭(Close)的MenuItem去除掉便可以了,去除後,又该如何Enable "X"呢,那
便是再将 关闭(Close)的MenuItem加回去,但这里有个小问题,加回去之後"X"仍是暗
灰色,要等到我们做了某些固定的动作之後(如TitleBar上click一下,或选一下System
Menu等),它才会再度变Enable的颜色,我不知道让TitleBar上的这些东西Refresh要送
什麽讯息,知道者请告诉我,所以现在我暂且Send一个在TitleBar上按下Mouse左键的讯
息给Form,令"X"能出现Enable的颜色。
 
‘需一个Command Button
Private Declare Function GetSystemMenu Lib "User32" (ByVal hwnd As Long, ByVal bRevert As Long) As Long
Private Declare Function deleteMenu Lib "User32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) As Long
Private Declare Function AppendMenu Lib "User32" Alias "AppendMenuA" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, ByVal lpNewItem As Any) As Long
Private Declare Function GetMenuString Lib "User32" Alias "GetMenuStringA" (ByVal hMenu As Long, ByVal wIDItem As Long, ByVal lpString As String, ByVal nMaxCount As Long, ByVal wFlag As Long) As Long
Private Declare Function SendMessage Lib "User32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
 
Const WM_NCLBUTTONDBLCLK = &HA3
Const WM_NCLBUTTONDOWN = &HA1
Const HTCAPTION = 2
Const MF_STRING = &H0&
Const MF_BYCOMMAND = &H0&
Const SC_CLOSE = &HF060
 
Private hMenu As Long
Private CloseStr As String ‘记录Close MenuItem的字串
 
‘将"关闭"的那一个MenuItem 加回来
Private Sub Command1_Click()
Call AppendMenu(hMenu, MF_STRING, SC_CLOSE, CloseStr)
 
‘令"X"能出现Enable的颜色
Call SendMessage(hwnd, WM_NCLBUTTONDOWN, HTCAPTION, 0&)
End Sub
 
Private Sub Form_Load()
hMenu = GetSystemMenu(Me.hwnd, 0)
CloseStr = String(255, 0)
 
‘SC_CLOSE指的便是"关闭"的那一个MenuItem ID
Call GetMenuString(hMenu, SC_CLOSE, CloseStr, 256, MF_BYCOMMAND)
CloseStr = Left(CloseStr, InStr(1, CloseStr, Chr(0)) – 1)
 
Call deleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND)
End Sub

One Comment

  1. May 2, 2009 at 5:28 pm

    This is very useful example of good programming using best practices. Thanks for sharing.

Leave a Reply