[MainViewModel.cs]
private void ExeWindowLoaded(RoutedEventArgs e)
{
if (e.OriginalSource is Window wnd)
{
WindowInteropHelper helper = new(wnd);
HwndSource source = HwndSource.FromHwnd(helper.Handle);
source.AddHook(new HwndSourceHook(WndProc));
}
}
MainView의 Window에 Loaded 이벤트에 해당 함수를 추가해준다.
private IntPtr WndProc(IntPtr hWnd, int nMsg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
uint WM_DEVICECHANGE = 0x0219;
uint DBT_DEVICEARRIVAL = 0x8000;
uint DBT_DEVICEREMOVECOMPLETE = 0x8004
if (nMsg == WM_DEVICECHANGE)
{
//장치 변동
int wparam = wParam.ToInt32();
if (wparam == DBT_DEVICEARRIVAL || wparam == DBT_DEVICEREMOVECOMPLETE)
{
if (wParam.ToInt32() == DBT_DEVICEARRIVAL)
{
//새로운 장치 감지
}
else if (wParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)
{
//장치 연결 해제됨.
}
}
}
return IntPtr.Zero;
}
WndProc에 이제 윈도우 메시지가 뜬다.
해당 코드는 PC에 장치가 연결 되고 해제되는 경우를 체크할 수 있는 함수이다.
실제로 이 코드를 통해서 연결이 불안한 USB 연결을 지속적으로 모니터링해서 변수에 대응할 수 있었다.
'SW개발 > c#' 카테고리의 다른 글
[WPF] CallerMemberName (Attribute) - Property 구현 (0) | 2023.02.20 |
---|---|
[WPF] Messenger 구현 (MVVM) (0) | 2023.02.17 |
[WPF] 모든 에러 발생시 이벤트 발생시키기 (0) | 2023.02.14 |
[C#] Logger (0) | 2023.01.31 |
[WPF] LED Light UI 코드 (2) | 2023.01.31 |