NEWS

[C#] Bắt sự kiện bật, tắt chương trình. Event start, stop process

[C#] Bắt sự kiện bật, tắt chương trình. Event start, stop process
Đăng bởi: Thảo Meo - Lượt xem: 11043 08:25:59, 24/09/2018C#   In bài viết

C# hỗ trợ người lập trình biết được chương trình nào vừa được bắt đầu, chương trình nào vừa kết thúc thông qua sự kiện EventArrivedEventHandler của ManagementEventWatcher nằm trong bộ thư viện System.Management.

Để bắt được các sự kiện này, đầu tiên chương trình phải có quyền admin. Để thực hiện gán quyền admin cho chương trình xem thêm .

[C#] Hướng dẫn chạy ứng dụng dưới quyền Administrator trong lập trình csharp

Sau khi thêm quyền admin cho chương trình, ta thoát visual ra và chạy lại nó với quyền admin
Chú ý: nếu không sử dụng được ManagementEventWatcher thì phải thực hiện Add reference System.Management bằng tay
Rồi, ok code như sau:

giám sát process
1. Bắt sự kiện chương trình mới được bật lên

void ChuongTrinhBat()
{
    WqlEventQuery q = new WqlEventQuery("Win32_ProcessStartTrace");
    ManagementEventWatcher w = new ManagementEventWatcher(q);
    w.EventArrived += new EventArrivedEventHandler(voidChuongTrinhBat);
    w.Start();
}

private void voidChuongTrinhTat(object sender, EventArrivedEventArgs e)
{
    string s = "";
    foreach (var pd in e.NewEvent.Properties)
        if(pd.Value != null)
            if (pd.Name == "ProcessName")// ngoai ra con co ProcessID, TIME_CREATED
                s += pd.Value.ToString() + "
";
    MessageBox.Show("Co mot chuong trinh vua moi tat
" + s);
}

2. Bắt sự kiện chương trình bị tắt đi

void ChuongTrinhTat()
{
    ManagementEventWatcher w1 = new ManagementEventWatcher("select ProcessName from Win32_ProcessStopTrace");
    w1.EventArrived += new EventArrivedEventHandler(voidChuongTrinhTat);
    w1.Start();
}
private void voidChuongTrinhBat(object sender, EventArrivedEventArgs e)
{
    string s = "";
    foreach (var pd in e.NewEvent.Properties)
        if (pd.Value != null)
            if (pd.Name == "ProcessName")// ngoai ra con co ProcessID, TIME_CREATED
                s += pd.Value.ToString() + "
";
    MessageBox.Show("Co mot chuong trinh vua moi bat
" + s);
}

- Ngoài ra có thể chỉnh lại cái đoạn select một chút để lấy những giá trị cần thiết như:
+ Lấy ProcessName: select ProcessName from Win32_ProcessStopTrace
+ Lấy thời gian: select TIME_CREATE from Win32_ProcessStartTrace

Theo http://thuvienwinform.blogspot.com

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Bắt sự kiện bật, tắt chương trình. Event start, stop process
Đăng bởi: Thảo Meo - Lượt xem: 11043 08:25:59, 24/09/2018C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.