寻找当前关注的应用

Finding Currently Focused Application

我一直在使用此代码来尝试获取当前进程 运行(除我的应用程序之外)。

整个互联网上都在告诉我使用下面的代码,但它似乎给我带来了问题。

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

[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

private string GetActiveWindowTitle()
{
    const int nChars = 256;
    StringBuilder Buff = new StringBuilder(nChars);
    IntPtr handle = GetForegroundWindow();

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

它给了我两个错误。

Expected class, delegate, enum, interface, or struct

The modifier 'extern' is not valid for this item

有人能帮忙吗?

Expected class, delegate, enum, interface, or struct

如果您遇到此错误,那么很可能您是在 namespace 中定义或声明这些方法,而不是在您的 class 正文中

如 Rahul 所述,将您的代码放入 class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{

    public partial class Form1 : Form
    {

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

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        public Form1()
        {
            InitializeComponent();
        }

        private string GetActiveWindowTitle()
        {
            const int nChars = 256;
            StringBuilder Buff = new StringBuilder(nChars);
            IntPtr handle = GetForegroundWindow();

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

        private void button1_Click(object sender, EventArgs e)
        {
            string title = GetActiveWindowTitle();
            label1.Text = title;
        }

    }

}