Rag*_*ock 2 vb.net listview focus listviewitem setfocus
如何以编程方式设置 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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,列表视图所在的表单还没有调用 ShowDialog 方法。这可能是它不起作用的原因吗?
您必须了解 Form 上的每个控件和 Form 本身都是一个窗口,要使窗口具有焦点,必须首先创建它并为其分配一个句柄。
对于这方面的基本描述,我建议您参阅: 关于 Windows 窗体中 的句柄以下摘录来自参考文章。
什么是手柄?
句柄 (HWND) 是 Windows 操作系统用来标识窗口的 CreateWindowEx 的返回值。win32 中的“窗口”是一个比您想象的更广泛的概念 - 每个单独的按钮、组合框、列表框等都包含一个窗口。(有关更多信息,请参阅关于窗口类) 注意:框架中还有其他称为“句柄”的内容 - 例如位图的 GDI 句柄或设备上下文 (HDC) 的句柄 - 本文仅讨论 HWND。
...
控件何时创建其句柄?(控件何时调用 CreateWindowEx?)
控件尽可能地尝试推迟创建其句柄。这是因为设置属性会强制 CLR 和 user32 之间进行繁琐的互操作。
通常在调用 Form.Load 事件之前创建所有控件的句柄。如果“Handle”属性被调用并且句柄尚未创建,或者 CreateControl() 被调用,也可以创建句柄。
因此,当您实例化控件时,不会立即创建窗口句柄。但是,您可以通过引用其Handle 属性来强制控件创建其句柄。
所以如果你首先让 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()
Run Code Online (Sandbox Code Playgroud)