iT邦幫忙

DAY 20
3

C# 程式學習系列 第 20

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

c#
  • 分享至 

  • xImage
  •  

撰寫程式,指定程序還原與置於前景視窗
如何撰寫程式來指定程序還原與置於前景視窗,可以透過 Windows API
(1)ShowWindowAsync : The ShowWindowAsync function sets the show state of a window created by a different thread.
(2)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.

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

上一篇
C# 設定螢幕解析度
下一篇
C# C#與VB程式碼互轉的網站
系列文
C# 程式學習30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言