小小鸭

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::
'添加 Command1和ListView1

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
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As Long, ByVal lpWindowName As Long) As Long
Private Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Const GW_HWNDNEXT = 2
Const LVM_FIRST As Long = &H1000
Const LVM_SETCOLUMNWIDTH As Long = (LVM_FIRST + 30)
Const LVSCW_AUTOSIZE_USEHEADER As Long = -2

Private Sub Form_Load()
    With ListView1
        .ListItems.Clear
        .ColumnHeaders.Clear
        .ColumnHeaders.Add , , "名称"
        .ColumnHeaders.Add , , "进程ID"
        .ColumnHeaders.Add , , "句 柄"
        .View = lvwReport
    End With
End Sub

Private Sub lvAutosizeControl(lv As ListView)
    Dim col2adjust&
    For col2adjust = 0 To lv.ColumnHeaders.Count - 1
        Call SendMessage(lv.hwnd, LVM_SETCOLUMNWIDTH, col2adjust, ByVal LVSCW_AUTOSIZE_USEHEADER)
    Next
End Sub

Private Sub Command1_Click()
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process")
    i = 1
    For Each objProcess In colProcesses
        Set itm = ListView1.ListItems.Add(1, "Row" & CStr(i), objProcess.Name)
        itm.SubItems(1) = CStr(objProcess.processid)
        itm.SubItems(2) = CStr(InstanceToWnd(objProcess.processid))
        i = i + 1
    Next
    Call lvAutosizeControl(ListView1) '把这行拿掉就可以看出Autosize是否生效
End Sub

Function InstanceToWnd(ByVal target_pid As Long) As Long
    Dim test_hwnd&, test_pid&, test_thread_id&
    test_hwnd = FindWindow(ByVal 0&, ByVal 0&)
    Do While test_hwnd <> 0
        If GetParent(test_hwnd) = 0 Then
            test_thread_id = GetWindowThreadProcessId(test_hwnd, test_pid)
            If test_pid = target_pid Then
                InstanceToWnd = test_hwnd
                Exit Do
            End If
        End If
        test_hwnd = GetWindow(test_hwnd, GW_HWNDNEXT)
    Loop
End Function

  

posted on 2012-06-29 15:49  小小鸭  阅读(1585)  评论(0)    收藏  举报