gpt4 book ai didi

vb.net - 如何以编程方式设置 ListView 焦点项目

转载 作者:行者123 更新时间:2023-12-02 00:58:57 28 4
gpt4 key购买 nike

如何以编程方式设置 FocusedItem 属性?

到目前为止,我已经试过了,但没有成功:

If lvw.FocusedItem Is Nothing Then
If lvw.Items.Count > 0 Then
lvw.Focus()
lvw.HideSelection = False
lvw.Items(0).Selected = True
lvw.Items(0).Focused = True
lvw.FocusedItem = lvw.Items(0)
lvw.Select()
End If
End If

顺便说一句, ListView 所在的表单还没有调用 ShowDialog 方法。这可能是这不起作用的原因吗?

最佳答案

您必须了解窗体上的每个控件和窗体本身都是一个窗口,要使窗口获得焦点,必须首先创建它并为其分配一个句柄。

有关这方面的基本描述,请引用:All About Handles in Windows Forms以下摘录自引用文章。

What is a Handle?

A handle (HWND) is the return value from CreateWindowEx which the Windows Operating System uses to identify a window. A "window" in win32 is a much broader concept than you may think - each individual button, combobox, listbox etc comprises a window. (For more information see About Window Classes ) NOTE: there are other things known as "Handles" in the Framework - e.g. GDI Handles from a Bitmap or Handles to Device Contexts (HDCs) - this article discusses HWNDs only.

...

When does a Control create its handle? (When does a control call CreateWindowEx?)

A control tries as much as possible to defer creating its handle. This is because setting properties forces chatty interop between the CLR and user32.

Typically the handles for all the controls are created before theForm.Load event is called. Handles can also be created if the "Handle"property is called and the handle has not yet been created, orCreateControl() is called.

因此,当您实例化控件时,不会立即创建窗口句柄。但是,您可以通过引用其 Handle property 来强制控件创建其句柄。 .

因此,如果您首先让 ListView 创建它的句柄,那么当您设置您想要的那些属性时。

Dim f2 As New Form2
' you do not need this condition, it is here only for demonstration purposes
' so that you can step through the code in the debugger and observe the
' code execution.
If Not f2.ListView1.IsHandleCreated Then
' retrieval of the Handle will cause a handle to be created
' if it has not yet been created
' if you delete the If-Then block, you will need to retain the
' following statement

Dim h As IntPtr = f2.ListView1.Handle
End If

f2.ListView1.FocusedItem = f2.ListView1.Items(2)
f2.ListView1.Items(2).Selected = True
f2.ListView1.Items(2).Focused = True
f2.ActiveControl = f2.ListView1
f2.ShowDialog()

关于vb.net - 如何以编程方式设置 ListView 焦点项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30937138/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com