.net - 如何获取进程的线程并将其显示在列表中
问题描述
因此,在 VB.NET 中,我想获取与进程关联的所有线程,因此我有一个文本框,在其中键入进程名称,然后单击按钮以在表单上的列表中获取与其关联的所有线程. 谢谢
我试图改变它并尝试在互联网上搜索它,但没有得到解决方案。
Imports System.Diagnostics
Imports System.Threading
Imports System.Windows.Forms
Imports System.ComponentModel
Public Class Form1
Private Sub ListThreads()
Try
Dim TheProcess As Process() = Process.GetProcessesByName(txtprocessName.Text)
MessageBox.Show(txtprocessName.Text)
Dim CurrentProcess As Process = Process.GetCurrentProcess()
Dim myThreads As ProcessThreadCollection = CurrentProcess.Threads
Dim thread As Process
threadList.BeginUpdate()
threadList.Clear()
'threadList.Columns.Add("Name", 100, HorizontalAlignment.Left)
threadList.Columns.Add("ID", 60, HorizontalAlignment.Left)
threadList.Columns.Add("Priority", 60, HorizontalAlignment.Right)
threadList.Columns.Add("Start Time", 100, HorizontalAlignment.Right)
For Each thread In myThreads
Dim lvi As ListViewItem = New ListViewItem()
'lvi.Text = thread.ProcessName
lvi.SubItems.Add(thread.Id)
lvi.SubItems.Add(thread.BasePriority)
lvi.SubItems.Add(thread.StartTime)
threadList.Items.Add(lvi)
Next thread
threadList.EndUpdate()
Catch e As Exception
MessageBox.Show(e.Message)
End Try
End Sub
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
ListThreads()
End Sub
End Class
每次我运行它都会显示一个错误
Unable to cast object of type System.Diagnostics.ProcessThread to type System.Diagnostics.Process
我想获取与进程关联的线程并将其显示在列表中。谢谢
解决方案
主要问题是因为类型thread
是Process
,但您返回的是ProcessThread
's ( Dim myThreads As ProcessThreadCollection = CurrentProcess.Threads
) 的集合,它们不一样。
要解决此问题,您有几个选择:
将类型更改
thread
为ProcessThread
。例如:(Dim thread As ProcessThread
这将修复实际错误)。完全删除变量
thread
并更改循环;你应该做这个。例如:For Each thread As ThreadProcess In myThreads
推荐阅读
- function - 创建一个函数确定等级
- c++ - 用大括号括起来的初始值设定项分配字符串时出错
- python - pow(a, b, c) 如何解决这个问题?
- html - 为什么此代码不以直线显示我的帖子?
- python - 生成 tf_record 时出错:AttributeError:模块 'tensorflow' 没有属性 'app'
- c - 为什么 __uint8_t 存在?
- google-drive-api - 谷歌驱动网址参数
- sql - SQL SELECT 语句不适用于 DELETE
- assembly - 16 位 8086 程序(bcc)小内存模型不适用于全局变量?
- amazon-web-services - AWS Lambda 多个触发器