Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#后台工作人员自行停止_C#_Multithreading_Hotkeys - Fatal编程技术网

C#后台工作人员自行停止

C#后台工作人员自行停止,c#,multithreading,hotkeys,C#,Multithreading,Hotkeys,我用C#编写了一个程序,可以启用几个全局热键,并根据按下的热键,激活chrome、firefox、记事本、计算器等窗口。注册全局热键后,我有一个无限的while循环,使应用程序保持活动状态。运行程序后,热键突然停止工作。这有时会在几个小时后发生。在长时间测试了我的每一段代码之后,我发现了这个问题。问题是主线程突然停止工作。该程序仍处于活动状态并在内存中。热键似乎是在另一个活动线程中注册的,即使包含while循环的主线程死了,它也能保持程序运行 然后我使用了backgroundworker,并在b

我用C#编写了一个程序,可以启用几个全局热键,并根据按下的热键,激活chrome、firefox、记事本、计算器等窗口。注册全局热键后,我有一个无限的while循环,使应用程序保持活动状态。运行程序后,热键突然停止工作。这有时会在几个小时后发生。在长时间测试了我的每一段代码之后,我发现了这个问题。问题是主线程突然停止工作。该程序仍处于活动状态并在内存中。热键似乎是在另一个活动线程中注册的,即使包含while循环的主线程死了,它也能保持程序运行

然后我使用了backgroundworker,并在backgroundworker中移动了while循环。这种情况再次发生,这意味着backgroundworker在热键仍在注册时突然停止。这不是我第一次使用backgroundworker,我从来没有遇到过backgroundworker独自退出的情况

发生这种情况时,类似这样的消息将出现在Visual Studio的输出窗口中:

The thread 0x1b24 has exited with code 0 (0x0)
线程是否有任何时间限制,以便它们在此之后退出? 你对这是如何发生的以及我如何解决它有什么建议吗

对于全局热键,我使用下面列出的代码:

http://stackoverflow.com/a/3654821/3179989
这是我代码的其余部分:

    public static void HotKeyPressed(object sender, HotKeyEventArgs e)
    {
        string PressedHotkey = e.Modifiers.ToString() + " " + e.Key.ToString();
        switch (PressedHotkey)
        {
            case "Alt D1":
                mActivateWindow(mEnumApplications.Chrome);
                break;
            case "Alt D3":
                mActivateWindow(mEnumApplications.CintaNotes);
                break;
            default:
                break;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bgWkrHotkey.WorkerSupportsCancellation = true;
        bgWkrHotkey.WorkerReportsProgress = true;
        bgWkrHotkey.RunWorkerAsync();
    }

    private void bgWkrHotkey_DoWork(object sender, DoWorkEventArgs e)
    {
        mHotKeyManager.RegisterHotKey(Keys.Oemtilde, KeyModifiers.Alt);
        mHotKeyManager.RegisterHotKey(Keys.D1, KeyModifiers.Alt);
        mHotKeyManager.RegisterHotKey(Keys.D3, KeyModifiers.Alt);
        mHotKeyManager.HotKeyPressed += new EventHandler<HotKeyEventArgs>(HotKeyPressed);

        while (true)
        {
            Thread.Sleep(50);
        }
    }

    //@@@@@@@@@@@@@@@@@@@@ DLL IMPORTS @@@@@@@@@@@@@@@@@@@@
    #region DLL IMPORTS
    [DllImport("User32.dll")]
    private static extern IntPtr SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

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

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

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

    [DllImport("USER32.DLL")]
    static extern IntPtr GetShellWindow();
    #endregion DLL IMPORTS

    public static IDictionary<IntPtr, string> mGetOpenWindows()
    {
        IntPtr ipShellWindow = GetShellWindow();
        Dictionary<IntPtr, string> ipWindows = new Dictionary<IntPtr, string>();

        EnumWindows(delegate(IntPtr hWnd, int lParam)
        {
            if (hWnd == ipShellWindow) return true;
            //if (!IsWindowVisible(hWnd)) return true;

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

            StringBuilder lBuilder = new StringBuilder(lLength);
            GetWindowText(hWnd, lBuilder, lLength + 1);

            ipWindows[hWnd] = lBuilder.ToString();
            return true;

        }, 0);

        return ipWindows;
    }

    public static string mGetActiveWindowTitle()
    {
        const int nChars = 256;
        StringBuilder Buff = new StringBuilder(nChars);
        IntPtr handle = GetForegroundWindow();

        if (GetWindowText(handle, Buff, nChars) > 0)
        {
            return Buff.ToString();
        }
        return "";
    }


    public static bool mActivateWindow(IntPtr ipHandle, string strWindowTitle)
    {
        StringBuilder Buff = new StringBuilder(256);
        SetForegroundWindow(ipHandle);

        Stopwatch swTimeout = new Stopwatch();
        swTimeout.Start();
        while (swTimeout.Elapsed < TimeSpan.FromSeconds(2))
        {
            ipHandle = GetForegroundWindow();
            if ((GetWindowText(ipHandle, Buff, 256) > 0) && (Buff.ToString().ToLower().Contains(strWindowTitle.ToLower())))
                return true;
            else
            {
                SetForegroundWindow(ipHandle);
                Thread.Sleep(50);
            }
        }
        swTimeout.Stop();
        return false;
    }

    public static bool mActivateWindow(mEnumApplications enumApp)
    {
        string strWindowTitle = "";
        switch (enumApp)
        {
            case mEnumApplications.Chrome:
                strWindowTitle = "Google Chrome";
                break;
            case mEnumApplications.CintaNotes:
                strWindowTitle = "CintaNotes";
                break;
            default:
                break;
        }

        IntPtr ipHandle = IntPtr.Zero;
        string strExactTitle = "";
        StringBuilder Buff = new StringBuilder(256);
        foreach (KeyValuePair<IntPtr, string> ipWindow in mGetOpenWindows())
        {
            ipHandle = ipWindow.Key;
            strExactTitle = ipWindow.Value;

            if (strExactTitle.ToLower().Contains(strWindowTitle.ToLower()))
                if (mActivateWindow(ipHandle, strWindowTitle))
                    return true;

        }
        return false;
    }

    public enum mEnumApplications
    {
        Null,
        Chrome,
        CintaNotes,
    };
publicstaticvoid热键按下(对象发送者,热键事件参数e)
{
字符串按热键=e.Modifiers.ToString()+“”+e.Key.ToString();
开关(按热键)
{
“备选D1”案:
mActivateWindow(mEnumApplications.Chrome);
打破
案例“Alt D3”:
mActivateWindow(mEnumApplications.CintaNotes);
打破
违约:
打破
}
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
bgWkrHotkey.WorkerSupportsCancellation=true;
bgWkrHotkey.WorkerReportsProgress=true;
bgWkrHotkey.RunWorkerAsync();
}
私有void bgWkrHotkey_DoWork(对象发送方,DoWorkEventArgs e)
{
mHotKeyManager.RegisterHotKey(Keys.Oemtilde,KeyModifiers.Alt);
mHotKeyManager.RegisterHotKey(Keys.D1,KeyModifiers.Alt);
mHotKeyManager.RegisterHotKey(Keys.D3,KeyModifiers.Alt);
mHotKeyManager.HotKeyPressed+=新事件处理程序(HotKeyPressed);
while(true)
{
睡眠(50);
}
}
//@@@@@@@@@@@@@@@@@@@@DLL导入@@@@@@@@@@@@@@@@@@@@
#区域DLL导入
[DllImport(“User32.dll”)]
私有静态外部IntPtr setforegroundindow(IntPtr hWnd);
[DllImport(“user32.dll”)]
静态外部IntPtr GetForegroundWindow();
委托bool EnumWindowsProc(IntPtr hWnd、intlparam);
[DllImport(“USER32.DLL”)]
静态外部布尔EnumWindows(EnumWindowsProc enumFunc,int lParam);
[DllImport(“USER32.DLL”)]
静态外部int GetWindowText(IntPtr hWnd、StringBuilder lpString、int nMaxCount);
[DllImport(“USER32.DLL”)]
静态外部int GetWindowTextLength(IntPtr hWnd);
[DllImport(“USER32.DLL”)]
静态外部IntPtr GetShellWindow();
#端域DLL导入
公共静态IDictionary管理开放窗口()
{
IntPtr ipShellWindow=GetShellWindow();
Dictionary ipWindows=新字典();
枚举窗口(委托(IntPtr hWnd、int lParam)
{
if(hWnd==ipshell窗口)返回true;
//如果(!IsWindowVisible(hWnd))返回true;
int lLength=GetWindowTextLength(hWnd);
如果(lLength==0)返回true;
StringBuilder lBuilder=新StringBuilder(lLength);
GetWindowText(hWnd、lBuilder、lLength+1);
ipWindows[hWnd]=lBuilder.ToString();
返回true;
}, 0);
返回ipWindows;
}
公共静态字符串mGetActiveWindowTitle()
{
常数int nChars=256;
StringBuilder Buff=新的StringBuilder(nChars);
IntPtr handle=getForeGroundIndow();
如果(GetWindowText(句柄、Buff、nChars)>0)
{
返回Buff.ToString();
}
返回“”;
}
公共静态bool mactivate窗口(IntPtr ipHandle,字符串strWindowTitle)
{
StringBuilder Buff=新的StringBuilder(256);
SetForeGroundindow(ipHandle);
秒表swTimeout=新秒表();
swTimeout.Start();
while(swTimeout.appeased0)和&(Buff.ToString().ToLower().Contains(strWindowTitle.ToLower()))
返回true;
其他的
{
SetForeGroundindow(ipHandle);
睡眠(50);
}
}
swTimeout.Stop();
返回false;
}
公共静态布尔mActivateWindow(MenuApplication enumApp)
{
字符串strWindowTitle=“”;
交换机(enumApp)
{
案例菜单应用程序。Chrome:
strWindowTitle=“谷歌浏览器”;
打破
案例菜单applications.CintaNotes:
strWindowTitle=“CintaNotes”;
打破
违约:
打破
}
IntPtr ipHandle=IntPtr.Zero;
字符串strExactTitle=“”;
StringBuilder Buff=新的StringBuilder(256);
foreach(mGetOpenWindows()中的KeyValuePair ipWindow)
{
ipHandle=ipWindow.Key;
strExactTitle=ipWindow.Value;
if(strExactTitle.ToLower().Contains(strWindowTitle.ToLower()))
if(mActivateWindow(ipHandle、strWindowTitle))
返回true;
}
返回false;
}
公共枚举菜单应用程序
{
无效的
铬,
辛塔诺特斯,
};
int lLength = GetWindowTextLength(hWnd);
if (lLength == 0) return true;
StringBuilder lBuilder = new StringBuilder(lLength+1);  // <-- changed to lLength+1
GetWindowText(hWnd, lBuilder, lLength + 1);
delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("USER32.DLL")]
static extern bool EnumWindows(EnumWindowsProc enumFunc, IntPtr lParam);