C# Force Form Focus

前端 未结 8 1966
不思量自难忘°
不思量自难忘° 2020-12-02 14:46

So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the sc

8条回答
  •  没有蜡笔的小新
    2020-12-02 15:27

    I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'm not sure if it will solve your problem.

    Basically, call ShowWindow() then SetForegroundWindow().

    using System.Diagnostics;
    using System.Runtime.InteropServices;
    
    // Sets the window to be foreground
    [DllImport("User32")]
    private static extern int SetForegroundWindow(IntPtr hwnd);
    
    // Activate or minimize a window
    [DllImportAttribute("User32.DLL")]
    private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    private const int SW_SHOW = 5;
    private const int SW_MINIMIZE = 6;
    private const int SW_RESTORE = 9;
    
    private void ActivateApplication(string briefAppName)
    {
        Process[] procList = Process.GetProcessesByName(briefAppName);
    
        if (procList.Length > 0)
        {
            ShowWindow(procList[0].MainWindowHandle, SW_RESTORE);
            SetForegroundWindow(procList[0].MainWindowHandle);
        }
    }
    

提交回复
热议问题