C #을 사용하여 현재 활성 창의 제목을 어떻게 얻습니까? 현재 활성 창 (즉, 포커스가있는 창)의

C #을 사용하여 현재 활성 창 (즉, 포커스가있는 창)의 창 제목을 잡는 방법을 알고 싶습니다.



답변

여기에서 전체 소스 코드로이를 수행하는 방법에 대한 예를 참조하십시오.

http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

private string GetActiveWindowTitle()
{
    const int nChars = 256;
    StringBuilder Buff = new StringBuilder(nChars);
    IntPtr handle = GetForegroundWindow();

    if (GetWindowText(handle, Buff, nChars) > 0)
    {
        return Buff.ToString();
    }
    return null;
}

더 나은 정확성을 위해 @Doug McClean 주석으로 편집 되었습니다.


답변

WPF에 대해 이야기하고 있다면 다음을 사용하십시오.

 Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);

답변

반복 Application.Current.Windows[]해서 IsActive == true.


답변

Windows API를 사용하십시오. 에게 전화하십시오 GetForegroundWindow().

GetForegroundWindow()hWnd활성 창에 대한 핸들 (이름 )을 제공합니다.

문서 : GetForegroundWindow 함수 | 마이크로 소프트 문서


답변

GetForegroundWindow 함수 기반 | Microsoft 문서 :

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowTextLength(IntPtr hWnd);

private string GetCaptionOfActiveWindow()
{
    var strTitle = string.Empty;
    var handle = GetForegroundWindow();
    // Obtain the length of the text   
    var intLength = GetWindowTextLength(handle) + 1;
    var stringBuilder = new StringBuilder(intLength);
    if (GetWindowText(handle, stringBuilder, intLength) > 0)
    {
        strTitle = stringBuilder.ToString();
    }
    return strTitle;
}

UTF8 문자를 지원합니다.


답변

MDI 응용 프로그램에서 현재 활성 양식 이 필요한 경우 : (MDI- 다중 문서 인터페이스).

Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;

답변

프로세스 클래스를 사용할 수 있습니다. 매우 쉽습니다. 이 네임 스페이스 사용

using System.Diagnostics;

활성 창을 얻기 위해 버튼을 만들고 싶다면.

private void button1_Click(object sender, EventArgs e)
    {
       Process currentp = Process.GetCurrentProcess();
       TextBox1.Text = currentp.MainWindowTitle;  //this textbox will be filled with active window.
    }