Tôi muốn biết cách lấy tiêu đề Cửa sổ của cửa sổ đang hoạt động hiện tại (tức là cửa sổ có tiêu điểm) bằng C #.
Tôi muốn biết cách lấy tiêu đề Cửa sổ của cửa sổ đang hoạt động hiện tại (tức là cửa sổ có tiêu điểm) bằng C #.
Câu trả lời:
Xem ví dụ về cách bạn có thể làm điều này với mã nguồn đầy đủ tại đây:
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;
}
Đã chỉnh sửa với nhận xét của @Doug McClean để có độ chính xác tốt hơn.
using System.Runtime.InteropServices;
và là nơi đặt các dòng nhập dll và tĩnh extern. dán nó trong lớp
Nếu bạn đang nói về WPF thì hãy sử dụng:
Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);
Sử dụng API Windows. GọiGetForegroundWindow()
.
GetForegroundWindow()
sẽ cung cấp cho bạn một xử lý (có tên hWnd
) đối với cửa sổ đang hoạt động.
Dựa trên chức năng GetForegroundWindow | Tài liệu 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;
}
Nó hỗ trợ các ký tự UTF8.
Nếu xảy ra trường hợp bạn cần Biểu mẫu Hoạt động Hiện tại từ ứng dụng MDI của mình : (MDI- Giao diện Đa tài liệu).
Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;
bạn có thể sử dụng lớp quy trình rất dễ dàng. sử dụng không gian tên này
using System.Diagnostics;
nếu bạn muốn tạo một nút để có được cửa sổ đang hoạt động.
private void button1_Click(object sender, EventArgs e)
{
Process currentp = Process.GetCurrentProcess();
TextBox1.Text = currentp.MainWindowTitle; //this textbox will be filled with active window.
}