在VB程式中,透過程式碼改變Combo控制元件只讀屬性Style值 (轉)

worldblog發表於2007-12-09
在VB程式中,透過程式碼改變Combo控制元件只讀屬性Style值 (轉)[@more@]

 

在VB中,如果你用如下語句動態建立一個Combo

Dim WithEvents cmbDropList As ComboBox
...
Set cmbDropList = Controls.Add("VB.ComboBox", "cmbDropList")
後,Combo控制元件的Style值是1 (VbComboDropDown 下拉式組合框,包括一個下拉式列表和一個文字框。可以從列表選擇或在文字框中輸入 ),若想把Style的值更改2 (VbComboDrop-DownList 2 下拉式列表。這種樣式僅允許從下拉式列表中選擇 )

透過語句Combo1.Style=2是不行的,因為Style是隻讀屬性。為了突破這個限制,我動用的Spy++這個武器,對兩種不同Style值的combo控制元件進行偵察,發現了兩處不同

  1、combo控制元件的style的值為1-VbComboDropDown時,combo控制元件視窗的Styles=&H54010242,而combo控制元件的style的值為2-VbComboDrop-DownList時,combo控制元件視窗的Styles=&H54010243

  2、combo控制元件的style的值為1-VbComboDropDown時,combo控制元件裡有一個Edit文字框視窗,而combo控制元件的style的值為2-VbComboDrop-DownList時,則沒有Edit文字框視窗

我首先試著用改變combo控制元件視窗的Styles值,

Call SetWindowLong(Combo1.hwnd, GWL_STYLE,&H54010243)

看Combo控制元件有沒有什麼改變,結果大失所望,

我再次試著用API函式殺死Combo控制元件裡的那個Edit視窗,耶~~~,成功了

下面是我的實現程式碼:

Private Const GWL_STYLE = (-16)
Private Const GW_CHILD = 5

Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function DestroyWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function CreateWindowEx Lib "user32" Alias "CreateWindowExA" (ByVal dwExStyle As Long, ByVal lpClassName As String, ByVal lpWindowName As String, ByVal dwStyle As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hWndParent As Long, ByVal hMenu As Long, ByVal hInstance As Long, lpParam As Any) As Long

Const SW_H = 0
Const SW_SHOW = 5

Dim WithEvents cmbDropList As ComboBox

Private Sub cmbDropList_Click()
  MsgBox cmbDropList.Text
End Sub

Private Sub Command1_Click()
  Dim ChildHwnd As Long
 
  Set cmbDropList = Controls.Add("VB.ComboBox", "cmbDropList")
 
  cmbDropList.Visible = True
  cmbDropList.AddItem "One"
  cmbDropList.AddItem "Two"
 
  ChildHwnd = GetWindow(cmbDropList.hwnd, GW_CHILD)  '取edit控制程式碼
  Call DestroyWindow(ChildHwnd)                      'Kill edit視窗
  '改變cmbDropList的Style,這一語句可有可無~~~~,
  Call SetWindowLong(cmbDropList.hwnd, GWL_STYLE, GetWindowLong(cmbDropList.hwnd, GWL_STYLE) + 1)

End Sub


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-990513/,如需轉載,請註明出處,否則將追究法律責任。

相關文章