在WPF检查列表框中获取实时运行流程

时间:2017-06-11 11:47:43

标签: c# wpf listbox

基本上我有这个代码,它在计时器中每2秒执行一次:

void GetAllPlayerWindows()
{
        Process[] processes = Process.GetProcessesByName("gamex");

        foreach (Process p in processes)
        {
            IntPtr windowHandle = p.MainWindowHandle;

            if (p.MainWindowTitle != "Login")
            {
                Character player = new Character();
                player.Handle = p.MainWindowHandle;
                player.Name = p.MainWindowTitle;
                lstPlayers.Items.Add(player);
            }
        }
}

这是Character类:

public class Character
{
    public string Name { get; set; } //MainWindowTitle
    public IntPtr Handle { get; set; } //MainWindowHandle
}

这是我的WPF检查列表框

<ListBox x:Name="lstPlayers" ItemsSource="{Binding playerList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Path=Item.Name}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

我无法弄清楚如何监控&#34; gamex&#34;处理并使其与列表框协调。因此,如果一个新进程生成它会创建一个项目,如果它被删除,它会删除它。由于GetAllPlayerWindows()每2秒执行一次,它会不断将每个进程添加到列表框中并进行重复。如何防止?

我想要实现的目标:

拥有一个总是更新并获取名为&#34; gamex&#34;的进程的列表框,获取theire mainwindowtitle并确保它不是&#34;登录&#34;。然后创建一个新的Character实例并放置Process Handle&amp;窗口标题为名称。并将此Character实例放在列表框中。这样我就可以访问它的项目并得到名称&amp;处理

2 个答案:

答案 0 :(得分:0)

在你的lstPlayers上做Find。如果它返回null,则该进程尚未在列表中,在这种情况下,您将添加它。

void GetAllPlayerWindows()
{
        Process[] processes = Process.GetProcessesByName("gamex");

        foreach (Process p in processes)
        {
            IntPtr windowHandle = p.MainWindowHandle;

            if (p.MainWindowTitle != "Login")
            {
                // find if the handle already is in the list
                if (lstPlayers.Find(i => i.Handle == windowHandle) == null)
                { 
                   // it is not, add it 
                   Character player = new Character();
                   player.Handle = p.MainWindowHandle;
                   player.Name = p.MainWindowTitle;
                   lstPlayers.Items.Add(player);
                }
            }
        }
}

答案 1 :(得分:0)

好的,我找到了自己的答案:

void GetAllPlayerWindows()
{
    Process[] processes = Process.GetProcessesByName("gamex");

    foreach (Process p in processes)
    {
        IntPtr windowHandle = p.MainWindowHandle;

        if (p.MainWindowTitle != "Login" && !ContainsHandle(p))//<--Made a little function
        {
            Character player = new Character();
            player.Handle = p.MainWindowHandle;
            player.Name = p.MainWindowTitle;
            lstPlayers.Items.Add(player);
        }
    }
}

bool ContainsHandle(Process p)
    {

        for (int i = 0; i < lstPlayers.Items.Count; i++)
        {
            Character player = lstPlayers.Items[i] as Character;
            if (player.Handle == p.MainWindowHandle)
                return true;
        }
        return false;
    }