정리가 필요한 카테고리(추후 정리)/C#,Unity

C#] 폼 포커싱(Form Focusing)

TwinParadox 2016. 11. 8. 22:51
728x90

C#을 활용해 프로그램을 만들다가

문득 윈도우를 최상위에 오게 만들 일이 생겼다.

소위 말해서 띄운 창에 포커싱을 해줘야 하는데,

속성값 몇 개 바꾼다고 해결될 줄 알았던 게 감감 무소식

Win API를 활용하는 방법이 있고

'TopMost'을 변경해주는 간단한 방법이 있다.



Win API 방식 활용


'using System.Runtime.InteropServices;' 빠뜨리지 말 것


 

1
2
3
4
5
6
// 윈도우가 비활성화 상태면 활성화 시켜야 포커싱
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
// 포커싱할 윈도우를 최상위에 오게 만듦
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
cs



설정을 잘못 건드려서 인지 이건 작동하지 않았다.

TopMost를 초기화를 하고 다시 바꾸는 방법을 택했는데, 원하는대로 작동했다.


'TopMost' 바꿔주기

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 초기화
private bool isTopMost=false;
// 포커싱 주고
this.Focus();
// TopMost가 true임에도 최상위에 위치하지 않을 경우, 토글을 통해 다시 작동
if(this.TopMost)
{
    isTopMost = true;
    this.TopMost = false;
    this.TopMost = true;
}
// TopMost가 false인 경우 true로 전환
else
{
    this.TopMost = true;
}
cs


사용하고 나서는 isTopMost와 TopMost를 다시 초기화시킬 것


728x90