[C#]指定程序還原與置於前景視窗

  • 20870
  • 0
  • 2010-08-02

指定程序還原與置於前景視窗

 

1. 問題說明

如何指定程序還原與置於前景視窗 ?

 

2. 方法

2.1 方法介紹

使用到的 WIndow API 中的

ShowWindowAsync : The ShowWindowAsync function sets the show state of a window created by a different thread.

SetForegroundWindow : The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window, and various visual cues are changed for the user. The system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.

使用 System.Diagnostics 中的

Process.GetProcesses 方法 : 為本機電腦上的每個處理序資源建立新的 Process 元件。

Process.ProcessName 屬性 : 取得處理序的名稱。

 

2.2 程式流程

使用者指定程序 -> 取得目前電腦的處理序 -> 取得處理序名稱並與指定程序名稱比較 -> 相同時透過ShowWindowAsync還原,以及SetForegroundWindow將程式至於前景

 

2.3 程式碼


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;   

namespace WindowsFormsApplication12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("User32.dll")]   
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);   
        [DllImport("User32.dll")]   
        private static extern bool SetForegroundWindow(IntPtr hWnd);   
        private const int WS_SHOWNORMAL = 1;  

        private void button1_Click(object sender, EventArgs e)
        {
            // 取得目前電腦的處理序
            foreach (Process pTarget in Process.GetProcesses())
            {
                if (pTarget.ProcessName == "KMPlayer")  // 取得處理序名稱並與指定程序名稱比較
                {
                    HandleRunningInstance(pTarget);
                }
            }
        }

        public static void HandleRunningInstance(Process instance)   
        {
            // 相同時透過ShowWindowAsync還原,以及SetForegroundWindow將程式至於前景
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
            SetForegroundWindow(instance.MainWindowHandle);   
        }   
    }
}

 

2.4 執行結果

未命名

 

2.5 程式下載

[C#]指定程序還原與置於前景視窗.rar