使用user32.dll 的Api,應用情境如以下:
在程式A上點擊按鈕後啟動B程式在背景執行,此時的焦點需要回到A程式
正常流程焦點會在B,透過以下方式可以將焦點設定為A
範例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Test
{
public partial class PlayVoice : Form
{
public PlayVoice()
{
InitializeComponent();
}
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "GetForegroundWindow", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetF(); //獲得本窗體的控制代碼
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetF(IntPtr hWnd); //設定此窗體為活動窗體
private void timer1_Tick(object sender, EventArgs e)
{
if (this.Handle != GetF()) //如果本視窗沒有獲得焦點
SetF(this.Handle); //設定本視窗獲得焦點
}
}
}
沒有留言:
張貼留言