크롬이나 엣지를 감지하여 따라다니는 프로그램 샘플입니다.
여러 개인 경우는 다르게 처리가 필요합니다 기능이 재미있어서 게시 해둬봅니다!
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class FollowForm : Form
{
// EnumWindows 콜백 델리게이트
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
//SetLastError 설정하면 아래와 같이 에러 타입 가져올 수 있습니다.
//int errorCode = Marshal.GetLastWin32Error();
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd,
IntPtr hWndInsertAfter,
int X,
int Y,
int cx,
int cy,
uint uFlags);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
const uint SWP_NOMOVE = 0x0002;
const uint SWP_NOSIZE = 0x0001;
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
//EntryPoint를 통해 C#에서 사용할 이름을 커스텀 할 수 있습니다.
[DllImport("user32.dll", EntryPoint = "GetWindowRect")]
private static extern bool GetWindowRect22(IntPtr hWnd, out RECT lpRect);
private bool isRunning = true;
public FollowForm()
{
InitializeComponent();
}
private void FollowForm_Load(object sender, EventArgs e)
{
IntPtr myHwnd = this.Handle;
Task.Run(async () =>
{
while (isRunning)
{
await Task.Delay(10);
EnumWindows((hWnd, lParam) => //최상위 윈도우 값들을 가져옵니다.
{
if (IsWindowVisible(hWnd)) //윈도우 보여지는지 여부
{
StringBuilder title = new StringBuilder(256);
GetWindowText(hWnd, title, title.Capacity); //윈도우 텍스트를 가져옵니다.
string windowTitle = title.ToString();
//크롬이나 엣지를 감지합니다.
if (windowTitle.Contains("Chrome") || windowTitle.Contains("Edge"))
{
Console.WriteLine(windowTitle);
SetWindowPos(hWnd, myHwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); //해당 위치를 조정해줍니다.
RECT rect;
GetWindowRect22(hWnd, out rect); //위치를 가져옵니다. GetWindowRect
Invoke((MethodInvoker)delegate
{
this.Location = new Point(rect.Left, rect.Top);
});
}
}
return true;
}, IntPtr.Zero);
}
});
}
private void FollowForm_FormClosing(object sender, FormClosingEventArgs e)
{
isRunning = false;
}
}
}'C# > Windows Form' 카테고리의 다른 글
| [C# Windows Form] Drag & Drop 기능 사용하기 (파일, 폴더 불러오기) (1) | 2025.08.15 |
|---|---|
| [C# Windows Form] Tray 아이콘 잔상 제거하기 (Win32 API 사용) (3) | 2025.07.29 |
| [C# Windows Form] 프로그램 Tray 아이콘 만들기, 감추기 (0) | 2025.07.16 |
| [C# Window Forms] App.config, appsettings.json 파일 값 저장 (0) | 2025.06.25 |
| [C# Windows Form] 32bit 프로그램 메모리 사용량 늘리기 (editbin.exe) (0) | 2025.05.29 |