按标题激活表单会引发System.NullReferenceException

时间:2015-10-20 04:12:54

标签: c# process combobox bringtofront

所以我有一个ComboBox的表单,我填充了一个打开进程列表(在这种情况下,我将其限制为标题为13个字符的进程。)当我选择{{1}时} Item我希望按标题和ComboBox找到Form但是当我这样做时,它会抛出BringToFront

这是我用来填充框的代码。

System.NullReferenceException

这是我用来试图展示表格的代码。

using HWND = IntPtr;
public static class OpenWindowGetter
{
    /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
    /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
    public static IDictionary<HWND, string> GetOpenWindows()
    {
        HWND shellWindow = GetShellWindow();
        Dictionary<HWND, string> windows = new Dictionary<HWND, string>();

        EnumWindows(delegate (HWND hWnd, int lParam)
        {
            if (hWnd == shellWindow) return true;
            if (!IsWindowVisible(hWnd)) return true;

            int length = GetWindowTextLength(hWnd);
            if (length == 0) return true;

            StringBuilder builder = new StringBuilder(length);
            GetWindowText(hWnd, builder, length + 1);

            windows[hWnd] = builder.ToString();
            return true;

        }, 0);

        return windows;
    }

    private delegate bool EnumWindowsProc(HWND hWnd, int lParam);

    [DllImport("USER32.DLL")]
    private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowTextLength(HWND hWnd);

    [DllImport("USER32.DLL")]
    private static extern bool IsWindowVisible(HWND hWnd);

    [DllImport("USER32.DLL")]
    private static extern IntPtr GetShellWindow();
}

public void populateIncidents()
    {
        foreach (KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
        {
            IntPtr handle = window.Key;
            string title = window.Value;
            if (title.Length == 13)
            {
                chooseIncidentBox.Items.Add(title);
            }
        }
    }

我不太确定为什么它会抛出异常,我知道Form存在,因为它不会填充private void chooseIncidentBox_SelectedIndexChanged(object sender, EventArgs e) { sSelectedIncident = chooseIncidentBox.Text; Application.OpenForms[sSelectedIncident].BringToFront(); //Exception thrown here. } 。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您拥有的代码会显示所有活动窗口。现在,Application.OpenForms仅适用于在您的应用程序中打开的表单。例如,如果您的应用中有ParentFormChildForm且两者都已打开,OpenForms集合将包含这两个。

您正在寻找的是将任何流程窗口放在前面。您可以在SetForegroundWindow中使用User32.dll来执行此操作。 This所以问题与您的需求非常相似。看看已接受的解决方案。