简体   繁体   English

使用DataGridView保留当前正在运行的进程的列表吗?

[英]Keeping a current list of running processes using a DataGridView?

I'm trying to make a program similar to task manager in C#. 我正在尝试使程序类似于C#中的任务管理器。 My current method is to get a list of processes at application startup, then get a new list if the user presses the "update" button. 我当前的方法是在应用程序启动时获取进程列表,然后在用户按下“更新”按钮时获取新列表。 I would like to keep a current list in my control instead, and "save" where the user has selected instead of the selection and the scroll bar being reset. 我想将当前列表保留在控件中,并“保存”用户选择的位置,而不是选择的位置和滚动条被重置。 What is a proper way of doing so in C#? 用C#这样做的正确方法是什么?

Here is how I currently update the control: 这是我当前更新控件的方式:

public void UpdateForm()
{
    processGridView.Rows.Clear();
    Process[] processes = Process.GetProcesses();

    for (int i = 0; i < processes.Length; ++i)
    {
        processGridView.Rows.Add();
        processGridView.Rows[i].Cells["processName"].Value = processes[i].ProcessName + ".exe";
        processGridView.Rows[i].Cells["processID"].Value = processes[i].Id;
    }
}

You mentioned in a comment that the real problem is with the refreshing of the GridView . 您在评论中提到,真正的问题在于GridView的刷新。 I suggest you look at using data binding . 我建议您看看使用数据绑定

EDIT a bit more code. 编辑更多代码。 But do read about data binding. 但是请阅读有关数据绑定的内容。 Here is the msdn page about the DataSource property. 是有关DataSource属性的msdn页面。 Note that you don't need sql database object, you can bind to a simple list. 请注意,您不需要sql数据库对象,可以绑定到简单列表。

Then, when your timer ticks and you have new data, reset the grid view data and binding. 然后,当计时器计时并且您有新数据时,请重置网格视图数据和绑定。 I found that the reset also resets the scroll bar, so I added code from this question to keep the scroll offset fixed. 我发现重设也会重设滚动条,因此我从这个问题中添加了代码以保持滚动偏移固定。 It's not great because the mouse loses control of the scroll bar during refresh. 这不是很好,因为在刷新过程中鼠标失去了对滚动条的控制。 I'll let you figure out a better solution. 我让您找出更好的解决方案。

public Form1()
{
  InitializeComponent();

  OnRefreshGrid(null, null);
  Timer ticker = new Timer();
  ticker.Interval = 250;
  ticker.Tick += OnRefreshGrid;
  ticker.Start();
}

void OnRefreshGrid(object sender, EventArgs e)
{
  BindingSource source = new BindingSource();
  var table = new DataTable("Process List");

  Process[] processes = Process.GetProcesses();

  table.Columns.Add("Name");
  table.Columns.Add("Id");

  for (int i = 0; i < processes.Length; ++i)
  {
    table.Rows.Add(new object[] { processes[i].ProcessName + ".exe", processes[i].Id });
  } 

  table.AcceptChanges();
  source.DataSource = table;

  int scroll = dataGridView1.FirstDisplayedScrollingRowIndex;
  dataGridView1.DataSource = source;

  if (scroll != -1)
    dataGridView1.FirstDisplayedScrollingRowIndex = scroll;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM