按标题激活表单抛出System.NullReferenceException

本文关键字:System NullReferenceException 表单 标题 激活 | 更新日期: 2023-09-27 18:18:30

所以我有一个带有ComboBox的表单,我用打开的进程列表填充它(在本例中,我将其限制为具有13个字符标题的进程)。当我在ComboBox中选择Item时,我想通过标题和BringToFront找到Form,但是当我这样做时,它会抛出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);
            }
        }
    }

下面是我用来显示表单的代码。

private void chooseIncidentBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        sSelectedIncident = chooseIncidentBox.Text;
        Application.OpenForms[sSelectedIncident].BringToFront(); //Exception thrown here.
    }

我不太确定为什么它抛出异常,我知道表单存在,因为它不会填充ComboBox否则。

按标题激活表单抛出System.NullReferenceException

您的代码给出了所有活动窗口。现在,Application.OpenForms只适用于在应用程序中打开的表单。例如,如果您的应用程序中有ParentFormChildForm,并且两者都是打开的,那么OpenForms集合将包含这两个。

你要找的是把任何进程窗口放在前面。您可以使用User32.dll中的SetForegroundWindow来完成此操作。这个SO问题看起来和你需要的非常相似。看一下被接受的解决方案。