2012/8/15

【C#】縮小命令提示字元視窗

今天同事提了個奇怪的需求:執行程式時要能把命令提是字元視窗縮小,查了一下網路發現可以利用FindWindow()與ShowWindow()兩個函數達成此需求,直接看以下範例:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace HideConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            IntPtr ParenthWnd = new IntPtr(0);
            
            ParenthWnd = Findindow(null, Console.Title);
            if (ParenthWnd == IntPtr.Zero)
                Console.WriteLine("Find Window ... FAIL");
            else
                ShowWindow(ParenthWnd, SW_SHOWMINIMIZED);
        }

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr Findindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", EntryPoint = "ShowWindow")]
        private static extern IntPtr ShowWindow(IntPtr hWnd, int type);
        const int SW_HIDE = 0;
        const int SW_SHOWMINIMIZED = 2;
        const int SW_MAXIMIZE = 3;
    }
}

流程說明:
  1. 用Console.Title找出命令提示字元視窗本身的標題字串,並透過FindWindow找出Handler
  2. 將Handler傳給ShowWindow函數,並傳入參數讓視窗進行改變,範例標了幾個視窗屬性SW_HIDE, SW_SHOWMINIMIZED與SW_MAXIMIZE,完整的參數可以參考MSDN的參考網頁( http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
因使用了DllImport,記得要加入
1
using System.Runtime.InteropServices;

Keyword:How to Minimize Terminal on Windows、C# Programming、Minimize Command Prompt on Windows

沒有留言:

張貼留言