Determine if current application is activated (has focus)

前端 未结 7 773
情歌与酒
情歌与酒 2020-11-27 15:26

Note: There\'s a very similar question, but it\'s WPF-specific; this one is not.

How can I determine if the current application is activ

7条回答
  •  抹茶落季
    2020-11-27 16:03

    First get the handle either using:

    IntPtr myWindowHandle;

    myWindowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
    

    or

    HwndSource source = (HwndSource)HwndSource.FromVisual(this);
    myWindowHandle = source.Handle;
    

    Then compare whethers it is the ForeGroundWindow:

    if (myWindowHandle == GetForegroundWindow()) 
    {
      // Do stuff!
    
    }
    
    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();
    

提交回复
热议问题