天天看點

C#調用windows api 窗體部分

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;

namespace AppCallWin32Api

{

    public partial class FormTest : Form

    {

        string title = getTitle();

        public FormTest()

        {

            InitializeComponent();

        }

        /// <summary>

        /// 開啟計時器

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnStrat_Click(object sender, EventArgs e)

        {

            this.tmrOne.Start();

        }

        /// <summary>

        /// 關閉計時器

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnStop_Click(object sender, EventArgs e)

        {

            this.tmrOne.Stop();

        }

        private void tmrOne_Tick(object sender, EventArgs e)

        {

            string temp = getTitle();

            if (!title.Equals(temp))

            {

                title = temp;

                this.lsbContent.Items.Add(title);

            }

        }

        [DllImport("user32.dll")]

        public extern static int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll")]

        public extern static IntPtr GetForegroundWindow();

        /// <summary>

        /// 擷取标題的靜态方法

        /// </summary>

        /// <returns></returns>

        static string getTitle()

        {

            StringBuilder str = new StringBuilder(512);

            //擷取目前運作的應用窗體的标題

            GetWindowText(GetForegroundWindow(), str, str.Capacity);

            //将标題傳回

            return str.ToString();

        }

    }

}