windows 获取进程列表的几种方式

windows 获取进程列表的几种方式,第1张

CreateToolhelp32Snapshot法:

// //////////////////////////////////////////////////////////////////////////

// // CreateToolhelp32Snapshot 法            #include <Tlhelp32.h>

// //////////////////////////////////////////////////////////////////////////

PROCESSENTRY32 pe32

pe32.dwSize = sizeof(PROCESSENTRY32)

BOOL bRet

HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,NULL)

bRet = Process32First(hProcessSnap,&pe32)

while (bRet)

{

bRet = Process32Next(hProcessSnap,&pe32)

printf("%s\n",&pe32.szExeFile)

}

return 0

如果想输出文件路径,在其中加入提权代码后再OpenProcess,GetModuleFileNameEx即可。

EnumProcesses 法

//////////////////////////////////////////////////////////////////////////

// EnumProcesses 法      #include <Psapi.h>  #pragma comment(lib,"Psapi.lib")

//////////////////////////////////////////////////////////////////////////

DWORD PID[1024]

DWORD needed,NumProcess

EnumProcesses(PID,sizeof(PID),&needed)

NumProcess = needed/sizeof(DWORD)

char FilePatch[MAX_PATH]

for (DWORD i=0i<NumProcessi++)

{

HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,FALSE,PID[i])

if (hProcess)

{

GetModuleFileNameEx(hProcess,NULL,FilePatch,sizeof(FilePatch))

printf("%s\n",FilePatch)

}

}

CloseHandle(hProcess)

printf("一共%d个进程\n",NumProcess)

return 0

WTSOpenServer 法

//////////////////////////////////////////////////////////////////////////

// WTSOpenServer 法   #include <Wtsapi32.h>#pragma comment(lib,"Wtsapi32.lib")   用nbtstat -an获取本机NetBios名称,并在命令行下输入即可

//////////////////////////////////////////////////////////////////////////

char *szServerName = argv[1]

PWTS_PROCESS_INFO wts

DWORD dwCount

HANDLE hWtsServer = WTSOpenServer(szServerName)

if(!WTSEnumerateProcesses(hWtsServer,0,1,&wts,&dwCount))

return 0

for (DWORD i=0i<dwCounti++)

{

printf("%s\n",wts[i].pProcessName) 

}

return 0

packageManager.getInstalledApplications()返回一个列表都是安装在设备上的应用程序包。如果我们把 flag GET_UNINSTALLED_PACKAGES设定,一个列表中的所有应用,包括那些设置为dont_delete_data(部分已安装的应用程序的数据目录)将返回。

你可以看到附件中的截图,我们将创建一个列表显示所有已安装的应用程序。

snippet_list_row.xml--------------------这个布局是由ListView适配器用于表示应用程序的细节。它显示应用程序图标、应用程序名称和应用程序包。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" ><ImageView android:id="@+id/app_icon" android:layout_width="50dp" android:layout_height="50dp" android:padding="3dp" android:scaleType="centerCrop" /><LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_vertical" android:orientation="vertical" android:paddingLeft="5dp" ><TextView android:id="@+id/app_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:textStyle="bold" /><TextView android:id="@+id/app_paackage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical" /></LinearLayout></LinearLayout>

AllAppsActivity.java ##这是用于初始化和列表已安装的应用程序的主要应用程序类。从packagemanage得到应用细节列表是一个耗时的任务,我们将在AsyncTask里面做。同时,类使用自定义适配器“自定义listview applicationadapter”。 package com.javatechig.listappsimport java.util.ArrayListimport java.util.Listimport android.app.AlertDialogimport android.app.ListActivityimport android.app.ProgressDialogimport android.content.ActivityNotFoundExceptionimport android.content.DialogInterfaceimport android.content.Intentimport android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.net.Uriimport android.os.AsyncTaskimport android.os.Bundleimport android.view.Menuimport android.view.MenuInflaterimport android.view.MenuItemimport android.view.Viewimport android.widget.ListViewimport android.widget.Toastpublic class AllAppsActivity extends ListActivity { private PackageManager packageManager = nullprivate List<ApplicationInfo>applist = nullprivate ApplicationAdapter listadaptor = null@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)packageManager = getPackageManager()new LoadApplications().execute()} public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater()inflater.inflate(R.menu.menu, menu)return true} public boolean onOptionsItemSelected(MenuItem item) { boolean result = trueswitch (item.getItemId()) { case R.id.menu_about: { displayAboutDialog()break} default: { result = super.onOptionsItemSelected(item)break} } return result} private void displayAboutDialog() { final AlertDialog.Builder builder = new AlertDialog.Builder(this)builder.setTitle(getString(R.string.about_title))builder.setMessage(getString(R.string.about_desc))builder.setPositiveButton("Know More", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://stacktips.com"))startActivity(browserIntent)dialog.cancel()} })builder.setNegativeButton("No Thanks!", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel()} })builder.show()} @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id)ApplicationInfo app = applist.get(position)try { Intent intent = packageManager .getLaunchIntentForPackage(app.packageName)if (null != intent) { startActivity(intent)} } catch (ActivityNotFoundException e) { Toast.makeText(AllAppsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show()} catch (Exception e) { Toast.makeText(AllAppsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show()} } private List<ApplicationInfo>checkForLaunchIntent(List<ApplicationInfo>list) { ArrayList<ApplicationInfo>applist = new ArrayList<ApplicationInfo>()for (ApplicationInfo info : list) { try { if (null != packageManager.getLaunchIntentForPackage(info.packageName)) { applist.add(info)} } catch (Exception e) { e.printStackTrace()} } return applist} private class LoadApplications extends AsyncTask<Void, Void, Void>{ private ProgressDialog progress = null@Override protected Void doInBackground(Void... params) { applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA))listadaptor = new ApplicationAdapter(AllAppsActivity.this, R.layout.snippet_list_row, applist)return null} @Override protected void onCancelled() { super.onCancelled()} @Override protected void onPostExecute(Void result) { setListAdapter(listadaptor)progress.dismiss()super.onPostExecute(result)} @Override protected void onPreExecute() { progress = ProgressDialog.show(AllAppsActivity.this, null, "Loading application info...")super.onPreExecute()} @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values)} }}

package com.javatechig.listappsimport java.util.Listimport android.content.Contextimport android.content.pm.ApplicationInfoimport android.content.pm.PackageManagerimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.ArrayAdapterimport android.widget.ImageViewimport android.widget.TextViewpublic class ApplicationAdapter extends ArrayAdapter<ApplicationInfo>{ private List<ApplicationInfo>appsList = nullprivate Context contextprivate PackageManager packageManagerpublic ApplicationAdapter(Context context, int textViewResourceId, List<ApplicationInfo>appsList) { super(context, textViewResourceId, appsList)this.context = contextthis.appsList = appsListpackageManager = context.getPackageManager()} @Override public int getCount() { return ((null != appsList) ? appsList.size() : 0)} @Override public ApplicationInfo getItem(int position) { return ((null != appsList) ? appsList.get(position) : null)} @Override public long getItemId(int position) { return position} @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertViewif (null == view) { LayoutInflater layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE)view = layoutInflater.inflate(R.layout.snippet_list_row, null)} ApplicationInfo applicationInfo = appsList.get(position)if (null != applicationInfo) { TextView appName = (TextView) view.findViewById(R.id.app_name)TextView packageName = (TextView) view.findViewById(R.id.app_paackage)ImageView iconview = (ImageView) view.findViewById(R.id.app_icon)appName.setText(applicationInfo.loadLabel(packageManager))packageName.setText(applicationInfo.packageName)iconview.setImageDrawable(applicationInfo.loadIcon(packageManager))} return view}}

Visual Basic是一种由微软公司开发的包含协助开发环境的事件驱动编程语言。

从任何标准来说,VB都是世界上使用人数最多的语言——不仅是盛赞VB的开发者还是抱怨VB的开发者的数量。

源自于BASIC编程语言。VB拥有图形用户界面(GUI)和快速应用程序开发(RAD)系统,可以轻易的使用DAO、RDO、ADO连接数据库,或者轻松的创建ActiveX控件。程序员可以轻松的使用VB提供的组件快速建立一个应用程序。

一个command 一个list。  list中第一个任务管理器,与最后一个Program Manager 过滤不掉 。

如果想过滤的话 可以在窗体中添加一个判断,来移除。

这是获取程序

Process[] ps=Process.GetProcesses()

foreach (Process p in ps)

{

if (p.MainWindowHandle != null)

{

richTextBox1.Text += p.MainWindowTitle + ""

}

}

#region 查找所有应用程序标题 private const int GW_HWNDFIRST = 0

private const int GW_HWNDNEXT = 2     

private const int GWL_STYLE = (-16)     

private const int WS_VISIBLE = 268435456     

private const int WS_BORDER = 8388608     

#region AIP声明        

[DllImport("IpHlpApi.dll")]        

extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder)     

[DllImport("User32")]        

private extern static int GetWindow(int hWnd, int wCmd)

[DllImport("User32")]        

private extern static int GetWindowLongA(int hWnd, int wIndx)

[DllImport("user32.dll")]        

private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize)       

[DllImport("user32", CharSet = CharSet.Auto)]        

private extern static int GetWindowTextLength(IntPtr hWnd)     

#endregion      

/// <summary>     

/// 查找所有应用程序标题      

/// </summary>     

/// <returns>应用程序标题范型</returns>     

public static List<string>FindAllApps(int Handle)

{          

List<string>Apps = new List<string>()         

int hwCurr           

hwCurr = GetWindow(Handle, GW_HWNDFIRST)         

while (hwCurr >0)          

{                

int IsTask = (WS_VISIBLE | WS_BORDER)               

int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE)             

bool TaskWindow = ((lngStyle &IsTask) == IsTask)             

if (TaskWindow)              

{                    

int length = GetWindowTextLength(new IntPtr(hwCurr))

StringBuilder sb = new StringBuilder(2 * length + 1)                 

GetWindowText(hwCurr, sb, sb.Capacity)                 

string strTitle = sb.ToString()               

if (!string.IsNullOrEmpty(strTitle))                  

{                        

Apps.Add(strTitle)                 

}              

}                

hwCurr = GetWindow(hwCurr, GW_HWNDNEXT)         

}

return Apps     

}        

#endregion

调用

private void btReApp_Click(object sender, EventArgs e)      

{            

LvApp.Items.Clear()           

List<string>Apps = SystemInfo.FindAllApps((int)this.Handle)         

foreach (string app in Apps)          

{                

ListViewItem item = new ListViewItem(app)             

LvApp.Items.Add(item)         

}      

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/11161010.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存