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,然后发布整个代码,而不是摘录,我只是不太确定我应该把它放在哪里,放在方法中还是放在类中@拉胡特汉克斯!我是这么做的,但我不知道是不是我搞砸了进口,但它现在起作用了,