Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.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#_.net_Interop - Fatal编程技术网

C# 查找当前关注的应用程序

C# 查找当前关注的应用程序,c#,.net,interop,C#,.net,Interop,我一直在使用此代码尝试获取当前正在运行的进程(我的应用程序除外) 在整个互联网上,它一直在告诉我使用下面的代码,但它似乎给了我一些问题 [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern int GetWindowText(IntPtr hWnd, StringBuilder text,

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

在整个互联网上,它一直在告诉我使用下面的代码,但它似乎给了我一些问题

[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;
}
这给了我两个错误

应为类、委托、枚举、接口或结构

修饰符“extern”对此项无效

有人能帮忙吗

应为类、委托、枚举、接口或结构


如果出现此错误,则很可能是在
名称空间中定义或声明这些方法,而不是在
类中定义或声明这些方法,如Rahul所述,请将代码放入类中:

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;
        }

    }

}

www.pinvoke.net即使在我的
公共部分类MainForm:Form
中,它也会给我这个错误@Rahul@SuperNovaa41,然后发布整个代码,而不是摘录,我只是不太确定我应该把它放在哪里,放在方法中还是放在类中@拉胡特汉克斯!我是这么做的,但我不知道是不是我搞砸了进口,但它现在起作用了,