[C#/COMMON/.NET8] 대용량 CSV 파일 병합하기
■ 대용량 CSV 파일을 병합하는 방법을 보여준다. ※ CSV 파일에 헤더 라인이 있어야 합니다. ※ 병합하는 CSV 파일은 동일한 헤더 라인을 갖고
■ 대용량 CSV 파일을 병합하는 방법을 보여준다. ※ CSV 파일에 헤더 라인이 있어야 합니다. ※ 병합하는 CSV 파일은 동일한 헤더 라인을 갖고
■ 엑셀에서 OLLAMA에게 질문을 하는 사용자 함수를 추가하는 방법을 보여준다. ▶ TestLibrary.csproj
1 2 3 4 5 6 7 8 9 10 11 12 |
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0-windows</TargetFramework> <ImplicitUsings>disable</ImplicitUsings> <Nullable>disable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="ExcelDna.AddIn" Version="1.8.0" /> </ItemGroup> </Project> |
▶ launchSettings.json
1 2 3 4 5 6 7 8 9 10 11 |
{ "profiles": { "Excel": { "commandName": "Executable", "executablePath": "C:\\Program Files\\Microsoft Office\\root\\Office16\\EXCEL.EXE", "commandLineArgs": "/x \"TestLibrary-AddIn64.xll\"" } } } |
▶ OllamaClient.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
using System.Net.Http; using System.Text; using System.Text.Json; namespace TestLibrary; /// <summary> /// OLLAMA 클라이언트 /// </summary> public class OllamaClient { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 기본 URL /// </summary> private readonly string baseURL; /// <summary> /// 모델명 /// </summary> private readonly string modelName; /// <summary> /// HTTP 클라이언트 /// </summary> private readonly HttpClient client; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - OllamaClient(baseURL, modelName) /// <summary> /// 생성자 /// </summary> /// <param name="baseURL">기본 URL</param> /// <param name="modelName">모델명</param> public OllamaClient(string baseURL = "http://localhost:11434", string modelName = "bnksys/eeve-yanolja-v1:latest") { this.baseURL = baseURL; this.modelName = modelName; this.client = new HttpClient(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 질문하기 - Ask(question) /// <summary> /// 질문하기 /// </summary> /// <param name="question">질문</param> /// <returns>답변</returns> public string Ask(string question) { var requestContent = new { model = this.modelName, prompt = question, stream = false, raw = false }; string json = JsonSerializer.Serialize(requestContent); StringContent stringContent = new StringContent(json, Encoding.UTF8, "application/json"); using(HttpResponseMessage httpResponseMessage = client.PostAsync($"{baseURL}/api/generate", stringContent).Result) { httpResponseMessage.EnsureSuccessStatusCode(); string respnseJSON = httpResponseMessage.Content.ReadAsStringAsync().Result; using(JsonDocument jsonElement = JsonDocument.Parse(respnseJSON)) { JsonElement rootJSONElement = jsonElement.RootElement; if(rootJSONElement.TryGetProperty("response", out JsonElement responseElement)) { return responseElement.GetString() ?? string.Empty; } return string.Empty; } } } #endregion } |
▶ CustomFunction.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using ExcelDna.Integration; namespace TestLibrary; /// <summary> /// 커스텀 함수 /// </summary> public static class CustomFunction { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region OLLAMA 질문하기 - AskOllama(question) /// <summary> /// OLLAMA 질문하기 /// </summary> /// <param name="question">질문</param> /// <returns>답변</returns> [ExcelFunction(Description = "Ollama에게 질문을 합니다.")] public static string AskOllama(string question) { OllamaClient ollamaClient = new OllamaClient(); string answer = ollamaClient.Ask(question); return answer; } #endregion } |
■ ExcelDna.AddIn 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ HttpClient 클래스를 사용해 OLLAMA 서버와 통신하는 방법을 보여준다. ▶ OllamaRequest.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using System.Text.Json.Serialization; namespace TestProject; /// <summary> /// OLLAMA 요청 /// </summary> public class OllamaRequest { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 모델 - Model /// <summary> /// 모델 /// </summary> [JsonPropertyName("model")] public string Model { get; set; } #endregion #region 프롬프트 - Prompt /// <summary> /// 프롬프트 /// </summary> [JsonPropertyName("prompt")] public string Prompt { get; set; } #endregion #region 스트림 여부 - Stream /// <summary> /// 스트림 여부 /// </summary> [JsonPropertyName("stream")] public bool Stream { get; set; } #endregion } |
▶ OllamaResponse.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using System.Text.Json.Serialization; namespace TestProject; /// <summary> /// OLLAMA 응답 /// </summary> public class OllamaResponse { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 모델 - Model /// <summary> /// 모델 /// </summary> [JsonPropertyName("model")] public string Model { get; set; } #endregion #region 응답 - Response /// <summary> /// 응답 /// </summary> [JsonPropertyName("response")] public string Response { get; set; } #endregion #region 완료 여부 - Done /// <summary> /// 완료 여부 /// </summary> [JsonPropertyName("done")] public bool Done { get; set; } #endregion } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace TestProject; /// <summary> /// 프로그램 /// </summary> public class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region OLLAMA 요청 보내기 (비동기) - SendOllamaRequestAsync(httpClient, ollamaRequest) /// <summary> /// OLLAMA 요청 보내기 (비동기) /// </summary> /// <param name="httpClient">HTTP 클라이언트</param> /// <param name="ollamaRequest">OLLAMA 요청</param> /// <returns>OLLAMA 응답 태스크</returns> private static async Task<OllamaResponse> SendOllamaRequestAsync(HttpClient httpClient, OllamaRequest ollamaRequest) { string json = JsonSerializer.Serialize ( ollamaRequest, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase } ); StringContent stringContent = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await httpClient.PostAsync("/api/generate", stringContent); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<OllamaResponse> ( responseBody, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase } ); } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> /// <returns>태스크</returns> private static async Task Main() { string baseURL = "http://localhost:11434"; using var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(baseURL); OllamaRequest ollamaRequest = new() { Model = "bnksys/eeve-yanolja-v1:latest", Prompt = "여기어때와 야놀자의 차이점을 알려주세요.", Stream = false }; try { OllamaResponse ollamaResponse = await SendOllamaRequestAsync(httpClient, ollamaRequest); Console.WriteLine($"질문 : {ollamaRequest.Prompt }"); Console.WriteLine($"응답 : {ollamaResponse.Response}"); } catch(Exception exception) { Console.WriteLine($"오류 발생 : {exception.Message}"); } } #endregion } |
TestProject.zip
■ 크롬 브라우저의 활성탭 웹 페이지에서 텍스트를 추출하는 방법을 보여준다. ▶ ChromBrowserProcessHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 |
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows; namespace TestProject; /// <summary> /// 크롬 브라우저 프로세스 헬퍼 /// </summary> public class ChromBrowserProcessHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Structure ////////////////////////////////////////////////////////////////////////////////////////// Private #region 사각형 - RECT /// <summary> /// 사각형 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct RECT { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 왼쪽 /// </summary> public int Left; /// <summary> /// 위쪽 /// </summary> public int Top; /// <summary> /// 오른쪽 /// </summary> public int Right; /// <summary> /// 아래쪽 /// </summary> public int Bottom; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Delegate ////////////////////////////////////////////////////////////////////////////////////////// Public #region 윈도우 나열하기 대리자 - EnumerateWindowDelegate(windowHandle, longParameter) /// <summary> /// 윈도우 나열하기 대리자 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="longParameter">LONG 매개 변수</param> /// <returns>처리 결과</returns> public delegate bool EnumerateWindowDelegate(IntPtr windowHandle, IntPtr longParameter); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 윈도우 열거하기 - EnumWindows(enumerateWindowDelegate, longParameter) /// <summary> /// 윈도우 열거하기 /// </summary> /// <param name="enumerateWindowDelegate">윈도우 열거하기 대리자</param> /// <param name="longParameter">LONG 매개 변수</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool EnumWindows(EnumerateWindowDelegate enumerateWindowDelegate, IntPtr longParameter); #endregion #region 윈도우 표시 여부 구하기 - IsWindowVisible(windowHandle) /// <summary> /// 윈도우 표시 여부 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>윈도우 표시 여부</returns> [DllImport("user32")] private static extern bool IsWindowVisible(IntPtr windowHandle); #endregion #region 윈도우 제목 구하기 - GetWindowText(windowHandle, stringBuilder, maximumCount) /// <summary> /// 윈도우 제목 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="stringBuilder">문자열 빌더</param> /// <param name="maximumCount">최대 카운트</param> /// <returns>처리 결과</returns> [DllImport("user32", SetLastError = true)] private static extern int GetWindowText(IntPtr windowHandle, StringBuilder stringBuilder, int maximumCount); #endregion #region 윈도우 사각형 구하기 - GetWindowRect(windowHandle, rectangle) /// <summary> /// 윈도우 사각형 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="rectangle">사각형</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool GetWindowRect(IntPtr windowHandle, out RECT rectangle); #endregion #region 활성 윈도우 설정하기 - SetForegroundWindow(windowHandle) /// <summary> /// 활성 윈도우 설정하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool SetForegroundWindow(IntPtr windowHandle); #endregion #region 윈도우 스레드 프로세스 ID 구하기 - GetWindowThreadProcessId(windowHandle, processID) /// <summary> /// 윈도우 스레드 프로세스 ID 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="processID">프로세스 ID</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern uint GetWindowThreadProcessId(IntPtr windowHandle, out uint processID); #endregion #region 윈도우 최소화 여부 구하기 - IsIconic(windowHandle) /// <summary> /// 윈도우 최소화 여부 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>윈도우 최소화 여부</returns> [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsIconic(IntPtr windowHandle); #endregion #region 윈도우 표시하기 - ShowWindow(windowHandle, showCommand) /// <summary> /// 윈도우 표시하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="showCommand">표시 명령</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool ShowWindow(IntPtr windowHandle, int showCommand); #endregion #region 전경 윈도우 구하기 - GetForegroundWindow() /// <summary> /// 전경 윈도우 구하기 /// </summary> /// <returns>전경 윈도우 핸들</returns> [DllImport("user32")] private static extern IntPtr GetForegroundWindow(); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SW_MAXIMIZE /// </summary> private const int SW_MAXIMIZE = 3; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 크롬 브라우저 윈도우 정보 리스트 구하기 - GetChromeBrowserWindowInfoList() /// <summary> /// 크롬 브라우저 윈도우 정보 리스트 구하기 /// </summary> /// <returns></returns> public static List<WindowInformation> GetChromeBrowserWindowInfoList() { List<WindowInformation> windowInformationList = new List<WindowInformation>(); EnumWindows ( delegate(IntPtr windowHandle, IntPtr longParameter) { if(IsWindowVisible(windowHandle)) { uint processID; GetWindowThreadProcessId(windowHandle, out processID); try { Process process = Process.GetProcessById((int)processID); if(process.ProcessName.ToLower().Contains("chrome")) { StringBuilder stringBuilder = new StringBuilder(256); GetWindowText(windowHandle, stringBuilder, 256); GetWindowRect(windowHandle, out RECT rectangle); int width = rectangle.Right - rectangle.Left; int height = rectangle.Bottom - rectangle.Top; windowInformationList.Add ( new WindowInformation { WindowHandle = windowHandle, Title = stringBuilder.ToString(), ProcessID = processID, Width = width, Height = height } ); } } catch(ArgumentException) { } } return true; }, IntPtr.Zero ); return windowInformationList; } #endregion #region 메인 크롬 브라우저 윈도우 정보 구하기 - GetMainChromeBrowserWindowInformation(windowInformationList) /// <summary> /// 메인 크롬 브라우저 윈도우 정보 구하기 /// </summary> /// <param name="windowInformationList">윈도우 정보 리스트</param> /// <returns>윈도우 정보</returns> public static WindowInformation GetMainChromeBrowserWindowInformation(List<WindowInformation> windowInformationList) { if(windowInformationList == null || windowInformationList.Count == 0) { return null; } WindowInformation mainWindowInformation = null; int maximumArea = 0; foreach(WindowInformation windowInformation in windowInformationList) { int area = windowInformation.Width * windowInformation.Height; if(area > maximumArea) { maximumArea = area; mainWindowInformation = windowInformation; } } return mainWindowInformation; } #endregion #region 윈도우 활성화 대기하기 - WaitForWindowActivation(targetWindowHandle, timeout) /// <summary> /// 윈도우 활성화 대기하기 /// </summary> /// <param name="targetWindowHandle">타겟 윈도우 핸들</param> /// <param name="timeout">타임아웃 (단위 : 초)</param> public static void WaitForWindowActivation(IntPtr targetWindowHandle, int timeout = 30) { var startTime = DateTime.Now; while((DateTime.Now - startTime).TotalSeconds < timeout) { IntPtr foregroundWindow = GetForegroundWindow(); if(foregroundWindow == targetWindowHandle) { return; } Thread.Sleep(100); } throw new TimeoutException("지정 시간 내에 윈도우를 활성화하는데 실패했습니다."); } #endregion #region 활성탭 텍스트 구하기 - GetActiveTabText(windowInformation) /// <summary> /// 활성탭 텍스트 구하기 /// </summary> /// <param name="windowInformation">윈도우 정보</param> /// <returns>텍스트</returns> public static string GetActiveTabText(WindowInformation windowInformation) { IntPtr windowHandle = windowInformation.WindowHandle; if(IsIconic(windowHandle)) { ShowWindow(windowHandle, SW_MAXIMIZE); } SetForegroundWindow(windowHandle); WaitForWindowActivation(windowHandle); MessageHelper.ClickMouse(windowHandle, 1, 150); System.Windows.Forms.SendKeys.SendWait("^{a}"); Thread.Sleep(500); System.Windows.Forms.SendKeys.SendWait("^{c}"); Thread.Sleep(100); string text = Clipboard.GetText(); Thread.Sleep(100); MessageHelper.ClickMouse(windowHandle, 0, 200); return text; } #endregion } |
▶ MessageHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
using System; using System.Runtime.InteropServices; using System.Threading; using System.Windows; namespace TestProject; /// <summary> /// 메시지 헬퍼 /// </summary> public static class MessageHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 활성 윈도우 설정하기 - SetForegroundWindow(windowHandle) /// <summary> /// 활성 윈도우 설정하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>처리 결과</returns> [DllImport("user32", SetLastError = true)] private static extern bool SetForegroundWindow(IntPtr windowHandle); #endregion #region 키보드 이벤트 발생시키기 - keybd_event(virtualKey, scanCode, flag, extraInformation) /// <summary> /// 키보드 이벤트 발생시키기 /// </summary> /// <param name="virtualKey">가상 키</param> /// <param name="scanCode">스캔 코드</param> /// <param name="flag">플래그</param> /// <param name="extraInformation">부가 정보</param> [DllImport("user32")] private static extern void keybd_event(byte virtualKey, byte scanCode, uint flag, uint extraInformation); #endregion #region 메시지 게시하기 - PostMessage(windowHandle, message, wordParameter, longParameter) /// <summary> /// 메시지 게시하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="message">메시지</param> /// <param name="wordParameter">WORD 매개 변수</param> /// <param name="longParameter">LONG 매개 변수</param> /// <returns>처리 결과</returns> [DllImport("user32", SetLastError = true)] private static extern bool PostMessage(IntPtr windowHandle, uint message, IntPtr wordParameter, IntPtr longParameter); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// VK_CONTROL /// </summary> private const byte VK_CONTROL = 0x11; /// <summary> /// KEYEVENTF_KEYUP /// </summary> private const int KEYEVENTF_KEYUP = 0x0002; /// <summary> /// VK_U /// </summary> private const byte VK_U = 0x55; /// <summary> /// VK_A /// </summary> private const byte VK_A = 0x41; /// <summary> /// VK_C /// </summary> private const byte VK_C = 0x43; /// <summary> /// VK_W /// </summary> private const byte VK_W = 0x57; /// <summary> /// WM_LBUTTONDOWN /// </summary> private const uint WM_LBUTTONDOWN = 0x0201; /// <summary> /// WM_LBUTTONUP /// </summary> private const uint WM_LBUTTONUP = 0x0202; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 마우스 클릭하기 - ClickMouse(windowHandle, x, y) /// <summary> /// 마우스 클릭하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="x">X</param> /// <param name="y">Y</param> public static void ClickMouse(IntPtr windowHandle, int x, int y) { PostMessage(windowHandle, WM_LBUTTONDOWN, IntPtr.Zero, MakeLongParameter(x, y)); Thread.Sleep(50); PostMessage(windowHandle, WM_LBUTTONUP, IntPtr.Zero, MakeLongParameter(x, y)); } #endregion #region 텍스트 구하기 - GetText(windowHandle) /// <summary> /// 텍스트 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>텍스트</returns> public static string GetText(IntPtr windowHandle) { if(windowHandle != IntPtr.Zero) { SetForegroundWindow(windowHandle); // CTRL + A 키 메시지를 보낸다. SendCTRLKeyCombination(VK_A); Thread.Sleep(500); // CTRL + C 키 메시지를 보낸다. SendCTRLKeyCombination(VK_C); Thread.Sleep(100); ClickMouse(windowHandle, 1, 150); string text = Clipboard.GetText(); return text; } else { return null; } } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region CTRL 키 조합 보내기 - SendCTRLKeyCombination(virtualKey) /// <summary> /// CTRL 키 조합 보내기 /// </summary> /// <param name="virtualKey">가상 키</param> private static void SendCTRLKeyCombination(byte virtualKey) { keybd_event(VK_CONTROL, 0, 0, 0); keybd_event(virtualKey, 0, 0, 0); keybd_event(virtualKey, 0, KEYEVENTF_KEYUP, 0); keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); } #endregion #region LONG 매개 변수 만들기 - MakeLongParameter(lowValue, highValue) /// <summary> /// LONG 매개 변수 만들기 /// </summary> /// <param name="lowValue">하위 값</param> /// <param name="highValue">상위 값</param> /// <returns>LONG 매개 변수</returns> private static IntPtr MakeLongParameter(int lowValue, int highValue) { return (IntPtr)((highValue << 16) | (lowValue & 0xffff)); } #endregion } |
▶ WindowHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; namespace TestProject; /// <summary> /// 윈도우 헬퍼 /// </summary> public static class WindowHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 활성 윈도우 설정하기 - SetForegroundWindow(windowHandle) /// <summary> /// 활성 윈도우 설정하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool SetForegroundWindow(IntPtr windowHandle); #endregion #region 윈도우 표시하기 - ShowWindow(windowHandle, command) /// <summary> /// 윈도우 표시하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="command">명령</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool ShowWindow(IntPtr windowHandle, int command); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SW_SHOW /// </summary> private const int SW_SHOW = 5; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 윈도우 앞으로 가져오기 - BringToFront(window) /// <summary> /// 윈도우 앞으로 가져오기 /// </summary> /// <param name="window">윈도우</param> public static void BringToFront(Window window) { WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window); nint windowHandle = windowInteropHelper.Handle; ShowWindow(windowHandle, SW_SHOW); SetForegroundWindow(windowHandle); } #endregion } |
▶ WindowInformation.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
using System; namespace TestProject; /// <summary> /// 윈도우 정보 /// </summary> public class WindowInformation { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 윈도우 핸들 - WindowHandle /// <summary> /// 윈도우 핸들 /// </summary> public IntPtr WindowHandle { get; set; } #endregion #region 제목 - Title /// <summary> /// 제목 /// </summary> public string Title { get; set; } #endregion #region 프로세스 ID - ProcessID /// <summary> /// 프로세스 ID /// </summary> public uint ProcessID { get; set; } #endregion #region 너비 - Width /// <summary> /// 너비 /// </summary> public int Width { get; set; } #endregion #region 높이 - Height /// <summary> /// 높이 /// </summary> public int Height { get; set; } #endregion } |
■ RegistryKey 클래스를 사용해 CUDA 설치 여부 및 CUDA 버전을 구하는 방법을 보여준다. ▶ CUDAHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
using Microsoft.Win32; namespace TestProject; /// <summary> /// CUDA 헬퍼 /// </summary> public class CUDAHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region CUDA 설치 여부 구하기 - IsCUDAInstalled() /// <summary> /// CUDA 설치 여부 구하기 /// </summary> /// <returns>CUDA 설치 여부</returns> public static bool IsCUDAInstalled() { try { #pragma warning disable CA1416 // 플랫폼 호환성 유효성 검사 using(RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\NVIDIA Corporation\GPU Computing Toolkit\CUDA")) { if(registryKey != null) { string[] subkeyNameArray = registryKey.GetSubKeyNames(); if(subkeyNameArray.Length > 0) { return true; } } } #pragma warning restore CA1416 // 플랫폼 호환성 유효성 검사 return false; } catch { return false; } } #endregion #region CUDA 버전 구하기 - GetGUDAVersion() /// <summary> /// CUDA 버전 구하기 /// </summary> /// <returns>CUDA 버전</returns> public static string GetGUDAVersion() { if(IsCUDAInstalled()) { #pragma warning disable CA1416 // 플랫폼 호환성 유효성 검사 using(RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\NVIDIA Corporation\GPU Computing Toolkit\CUDA")) { if(registryKey != null) { string[] subkeyNameArray = registryKey.GetSubKeyNames(); if(subkeyNameArray.Length > 0) { string version = string.Join(", ", subkeyNameArray); return version; } } } #pragma warning restore CA1416 // 플랫폼 호환성 유효성 검사 return null; } else { return null; } } #endregion } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
using System; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> static void Main() { bool isCUDAInstalled = CUDAHelper.IsCUDAInstalled(); if(isCUDAInstalled) { Console.WriteLine("CUDA가 설치되어 있습니다."); string version = CUDAHelper.GetGUDAVersion(); Console.WriteLine($"CUDA 버전 : {version}"); } else { Console.WriteLine("CUDA가 설치되어 있지 않습니다."); } } #endregion } |
TestProject.zip
■ Window 클래스에서 윈도우를 화면 왼쪽에 고정하고 나머지 영역을 작업 영역으로 설정하는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> </Window> |
▶ MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; namespace TestProject; /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Structure ////////////////////////////////////////////////////////////////////////////////////////// Private #region 사각형 - RECT /// <summary> /// 사각형 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct RECT { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 왼쪽 /// </summary> public int Left; /// <summary> /// 위쭉 /// </summary> public int Top; /// <summary> /// 오른쪽 /// </summary> public int Right; /// <summary> /// 아래쪽 /// </summary> public int Bottom; #endregion } #endregion #region 모니터 정보 - MONITOR_INFORMATION /// <summary> /// 모니터 정보 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct MONITOR_INFORMATION { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 크기 /// </summary> public uint Size; /// <summary> /// 모니터 사각형 /// </summary> public RECT MonitorRectangle; /// <summary> /// 작업 영역 사각형 /// </summary> public RECT WorkAreaRectangle; /// <summary> /// 플래그 /// </summary> public uint Flag; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 시스템 메트릭스 구하기 - GetSystemMetrics(index) /// <summary> /// 시스템 메트릭스 구하기 /// </summary> /// <param name="index">인덱스</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern int GetSystemMetrics(int index); #endregion #region 윈도우에서 모니터 구하기 - MonitorFromWindow(windowHandle, flag) /// <summary> /// 윈도우에서 모니터 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="flag">플래그</param> /// <returns>모니터 핸들</returns> [DllImport("user32")] private static extern IntPtr MonitorFromWindow(IntPtr windowHandle, uint flag); #endregion #region 모니터 정보 구하기 - GetMonitorInfo(monitorHandle, monitorInformation) /// <summary> /// 모니터 정보 구하기 /// </summary> /// <param name="monitorHandle">모니터 핸들</param> /// <param name="monitorInformation">모니터 정보</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool GetMonitorInfo(IntPtr monitorHandle, ref MONITOR_INFORMATION monitorInformation); #endregion #region 시스템 매개 변수 정보 설정하기 - SystemParametersInfo(action, parameter1, parameter2, flag) /// <summary> /// 시스템 매개 변수 정보 설정하기 /// </summary> /// <param name="action">액션</param> /// <param name="parameter1">매개 변수 1</param> /// <param name="parameter2">매개 변수 2</param> /// <param name="flag">플래그</param> /// <returns>처리 결과</returns> [DllImport("user32", SetLastError = true)] private static extern bool SystemParametersInfo(uint action, uint parameter1, IntPtr parameter2, uint flag); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SM_CXSCREEN /// </summary> private const int SM_CXSCREEN = 0; /// <summary> /// SM_CYSCREEN /// </summary> private const int SM_CYSCREEN = 1; /// <summary> /// MONITOR_DEFAULTTONEAREST /// </summary> private const uint MONITOR_DEFAULTTONEAREST = 2; /// <summary> /// SPI_SETWORKAREA /// </summary> private const uint SPI_SETWORKAREA = 0x002F; /// <summary> /// 원본 작업 영역 사각형 /// </summary> private RECT originalWorkAreaRectangle; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { InitializeComponent(); Loaded += Window_Loaded; Closing += Window_Closing; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 윈도우 로드시 처리하기 - Window_Loaded(sender, e) /// <summary> /// 윈도우 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Window_Loaded(object sender, RoutedEventArgs e) { SetWindowPosition(); SetWorkArea(); SetTopMostWindow(); } #endregion #region 윈도우 닫을 경우 처리하기 - Window_Closing(sender, e) /// <summary> /// 윈도우 닫을 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Window_Closing(object sender, CancelEventArgs e) { RestoreWorkArea(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 윈도우 위치 설정하기 - SetWindowPosition() /// <summary> /// 윈도우 위치 설정하기 /// </summary> private void SetWindowPosition() { IntPtr windowHandle = new WindowInteropHelper(this).Handle; IntPtr monitorHandle = MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST); MONITOR_INFORMATION monitorInformation = new MONITOR_INFORMATION(); monitorInformation.Size = (uint)Marshal.SizeOf(typeof(MONITOR_INFORMATION)); GetMonitorInfo(monitorHandle, ref monitorInformation); RECT workAreaRectangle = monitorInformation.WorkAreaRectangle; Width = 400 + 7; Height = workAreaRectangle.Bottom - workAreaRectangle.Top + 7; Left = workAreaRectangle.Right - 400; Top = workAreaRectangle.Top; } #endregion #region 작업 영역 설정하기 - SetWorkArea() /// <summary> /// 작업 영역 설정하기 /// </summary> private void SetWorkArea() { IntPtr windowHandle = new WindowInteropHelper(this).Handle; IntPtr monitorHandle = MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST); MONITOR_INFORMATION monitorInformation = new MONITOR_INFORMATION(); monitorInformation.Size = (uint)Marshal.SizeOf(typeof(MONITOR_INFORMATION)); GetMonitorInfo(monitorHandle, ref monitorInformation); this.originalWorkAreaRectangle = monitorInformation.WorkAreaRectangle; RECT workAreaRectangle = monitorInformation.WorkAreaRectangle; workAreaRectangle.Right -= (int)Width; IntPtr workAreaRectangleHandle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(RECT))); Marshal.StructureToPtr(workAreaRectangle, workAreaRectangleHandle, false); SystemParametersInfo(SPI_SETWORKAREA, 0, workAreaRectangleHandle, 0); Marshal.FreeHGlobal(workAreaRectangleHandle); } #endregion #region 작업 영역 복원하기 - RestoreWorkArea() /// <summary> /// 작업 영역 복원하기 /// </summary> private void RestoreWorkArea() { IntPtr workAreaRectangleHandle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(RECT))); Marshal.StructureToPtr(originalWorkAreaRectangle, workAreaRectangleHandle, false); SystemParametersInfo(SPI_SETWORKAREA, 0, workAreaRectangleHandle, 0); Marshal.FreeHGlobal(workAreaRectangleHandle); } #endregion #region 최상위 윈도우 설정하기 - SetTopMostWindow() /// <summary> /// 최상위 윈도우 설정하기 /// </summary> private void SetTopMostWindow() { Topmost = true; } #endregion } |
TestProject.zip
■ 크롬 브라우저의 활성탭 웹 페이지에서 텍스트를 추출하는 방법을 보여준다. ▶ ChromBrowserProcessHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace TestProject; /// <summary> /// 크롬 브라우저 프로세스 헬퍼 /// </summary> public class ChromBrowserProcessHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Structure ////////////////////////////////////////////////////////////////////////////////////////// Private #region 사각형 - RECT /// <summary> /// 사각형 /// </summary> [StructLayout(LayoutKind.Sequential)] private struct RECT { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 왼쪽 /// </summary> public int Left; /// <summary> /// 위쪽 /// </summary> public int Top; /// <summary> /// 오른쪽 /// </summary> public int Right; /// <summary> /// 아래쪽 /// </summary> public int Bottom; #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Delegate ////////////////////////////////////////////////////////////////////////////////////////// Public #region 윈도우 나열하기 대리자 - EnumerateWindowDelegate(windowHandle, longParameter) /// <summary> /// 윈도우 나열하기 대리자 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="longParameter">LONG 매개 변수</param> /// <returns>처리 결과</returns> public delegate bool EnumerateWindowDelegate(IntPtr windowHandle, IntPtr longParameter); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 윈도우 열거하기 - EnumWindows(enumerateWindowDelegate, longParameter) /// <summary> /// 윈도우 열거하기 /// </summary> /// <param name="enumerateWindowDelegate">윈도우 열거하기 대리자</param> /// <param name="longParameter">LONG 매개 변수</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool EnumWindows(EnumerateWindowDelegate enumerateWindowDelegate, IntPtr longParameter); #endregion #region 윈도우 표시 여부 구하기 - IsWindowVisible(windowHandle) /// <summary> /// 윈도우 표시 여부 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>윈도우 표시 여부</returns> [DllImport("user32")] private static extern bool IsWindowVisible(IntPtr windowHandle); #endregion #region 윈도우 제목 구하기 - GetWindowText(windowHandle, stringBuilder, maximumCount) /// <summary> /// 윈도우 제목 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="stringBuilder">문자열 빌더</param> /// <param name="maximumCount">최대 카운트</param> /// <returns>처리 결과</returns> [DllImport("user32", SetLastError = true)] private static extern int GetWindowText(IntPtr windowHandle, StringBuilder stringBuilder, int maximumCount); #endregion #region 윈도우 사각형 구하기 - GetWindowRect(windowHandle, rectangle) /// <summary> /// 윈도우 사각형 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="rectangle">사각형</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool GetWindowRect(IntPtr windowHandle, out RECT rectangle); #endregion #region 활성 윈도우 설정하기 - SetForegroundWindow(windowHandle) /// <summary> /// 활성 윈도우 설정하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool SetForegroundWindow(IntPtr windowHandle); #endregion #region 윈도우 스레드 프로세스 ID 구하기 - GetWindowThreadProcessId(windowHandle, processID) /// <summary> /// 윈도우 스레드 프로세스 ID 구하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="processID">프로세스 ID</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern uint GetWindowThreadProcessId(IntPtr windowHandle, out uint processID); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 크롬 브라우저 윈도우 정보 리스트 구하기 - GetChromeBrowserWindowInfoList() /// <summary> /// 크롬 브라우저 윈도우 정보 리스트 구하기 /// </summary> /// <returns></returns> public static List<WindowInformation> GetChromeBrowserWindowInfoList() { List<WindowInformation> windowInformationList = new List<WindowInformation>(); EnumWindows ( delegate(IntPtr windowHandle, IntPtr longParameter) { if(IsWindowVisible(windowHandle)) { uint processID; GetWindowThreadProcessId(windowHandle, out processID); try { Process process = Process.GetProcessById((int)processID); if(process.ProcessName.ToLower().Contains("chrome")) { StringBuilder stringBuilder = new StringBuilder(256); GetWindowText(windowHandle, stringBuilder, 256); GetWindowRect(windowHandle, out RECT rectangle); int width = rectangle.Right - rectangle.Left; int height = rectangle.Bottom - rectangle.Top; windowInformationList.Add ( new WindowInformation { WindowHandle = windowHandle, Title = stringBuilder.ToString(), ProcessID = processID, Width = width, Height = height } ); } } catch(ArgumentException) { } } return true; }, IntPtr.Zero ); return windowInformationList; } #endregion #region 메인 크롬 브라우저 윈도우 정보 구하기 - GetMainChromeBrowserWindowInformation(windowInformationList) /// <summary> /// 메인 크롬 브라우저 윈도우 정보 구하기 /// </summary> /// <param name="windowInformationList">윈도우 정보 리스트</param> /// <returns>윈도우 정보</returns> public static WindowInformation GetMainChromeBrowserWindowInformation(List<WindowInformation> windowInformationList) { if(windowInformationList == null || windowInformationList.Count == 0) { return null; } WindowInformation mainWindowInformation = null; int maximumArea = 0; foreach(WindowInformation windowInformation in windowInformationList) { int area = windowInformation.Width * windowInformation.Height; if(area > maximumArea) { maximumArea = area; mainWindowInformation = windowInformation; } } return mainWindowInformation; } #endregion #region 활성탭 정보 구하기 - GetActiveTabInformation(windowInformation) /// <summary> /// 활성탭 정보 구하기 /// </summary> /// <param name="windowInformation">윈도우 정보</param> /// <returns>URL/HTML 튜플</returns> public static (string url, string html) GetActiveTabInformation(WindowInformation windowInformation) { IntPtr windowHandle = windowInformation.WindowHandle; SetForegroundWindow(windowHandle); Thread.Sleep(300); // ALT 키를 누른다. System.Windows.Forms.SendKeys.SendWait("%"); Thread.Sleep(100); // 주소 창을 선택한다. System.Windows.Forms.SendKeys.SendWait("^{l}"); Thread.Sleep(10); // URL을 복사한다. System.Windows.Forms.SendKeys.SendWait("^{c}"); Thread.Sleep(10); // 클립보드에서 URL을 구한다. string url = System.Windows.Forms.Clipboard.GetText(); // 소스 보기 창을 연다. System.Windows.Forms.SendKeys.SendWait("^{u}"); Thread.Sleep(1000); // 전체 문자열을 선택한다. System.Windows.Forms.SendKeys.SendWait("^{a}"); Thread.Sleep(500); // HTML을 복사한다. System.Windows.Forms.SendKeys.SendWait("^{c}"); Thread.Sleep(100); // 클립보드에서 HTML을 가져온다. string html = System.Windows.Forms.Clipboard.GetText(); // 소스 창을 닫는다. System.Windows.Forms.SendKeys.SendWait("^{w}"); return (url, html); } #endregion } |
▶ HTMLHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
using System; using System.Linq; using System.Text.RegularExpressions; using HtmlAgilityPack; namespace TestProject; /// <summary> /// HTML 헬퍼 /// </summary> public class HTMLHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 텍스트 추출하기 - ExtractText(html) /// <summary> /// 텍스트 추출하기 /// </summary> /// <param name="html">HTML</param> /// <returns>텍스트</returns> public static string ExtractText(string html) { HtmlDocument htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); return htmlDocument.DocumentNode.InnerText; } #endregion #region 문자열 정규화하기 - NormalizeString(sourceString) /// <summary> /// 문자열 정규화하기 /// </summary> /// <param name="sourceString">소스 문자열</param> /// <returns>정규화 문자열</returns> /// <remarks> /// 1. 각 줄의 문자열의 앞뒤 공백을 제거한다. /// 2. 빈줄이 반복되는 경우 1개의 빈줄로 만든다. /// </remarks> public static string NormalizeString(string sourceString) { string[] sourceLineArray = sourceString.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); string[] targetLineArray = sourceLineArray.Select(line => line.Trim()).ToArray(); string joinedString = string.Join(Environment.NewLine, targetLineArray); string targetString = Regex.Replace(joinedString, @"(\r\n|\n){2,}", Environment.NewLine + Environment.NewLine); return targetString; } #endregion } |
▶ WindowHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; namespace TestProject; /// <summary> /// 윈도우 헬퍼 /// </summary> public static class WindowHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 활성 윈도우 설정하기 - SetForegroundWindow(windowHandle) /// <summary> /// 활성 윈도우 설정하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool SetForegroundWindow(IntPtr windowHandle); #endregion #region 윈도우 표시하기 - ShowWindow(windowHandle, command) /// <summary> /// 윈도우 표시하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="command">명령</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool ShowWindow(IntPtr windowHandle, int command); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SW_SHOW /// </summary> private const int SW_SHOW = 5; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 윈도우 앞으로 가져오기 - BringToFront(window) /// <summary> /// 윈도우 앞으로 가져오기 /// </summary> /// <param name="window">윈도우</param> public static void BringToFront(Window window) { WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window); nint windowHandle = windowInteropHelper.Handle; ShowWindow(windowHandle, SW_SHOW); SetForegroundWindow(windowHandle); } #endregion } |
▶ WindowInformation.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
using System; namespace TestProject; /// <summary> /// 윈도우 정보 /// </summary> public class WindowInformation { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 윈도우 핸들 - WindowHandle /// <summary> /// 윈도우 핸들 /// </summary> public IntPtr WindowHandle { get; set; } #endregion #region 제목 - Title /// <summary> /// 제목 /// </summary> public string Title { get; set; } #endregion #region 프로세스 ID - ProcessID /// <summary> /// 프로세스 ID /// </summary> public uint ProcessID { get; set; } #endregion #region 너비 - Width /// <summary> /// 너비 /// </summary> public int Width { get; set; } #endregion #region 높이 - Height /// <summary> /// 높이 /// </summary> public int Height { get; set; } #endregion } |
■ String 클래스에서 문자열을 정규화하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Linq; using System.Text.RegularExpressions; #region 문자열 정규화하기 - NormalizeString(sourceString) /// <summary> /// 문자열 정규화하기 /// </summary> /// <param name="sourceString">소스 문자열</param> /// <returns>정규화 문자열</returns> /// <remarks> /// 1. 각 줄의 문자열의 앞뒤 공백을 제거한다. /// 2. 빈줄이 반복되는 경우 1개의 빈줄로 만든다. /// </remarks> public string NormalizeString(string sourceString) { string[] sourceLineArray = sourceString.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); string[] targetLineArray = sourceLineArray.Select(line => line.Trim()).ToArray(); string joinedString = string.Join(Environment.NewLine, targetLineArray); string targetString = Regex.Replace(joinedString, @"(\r\n|\n){2,}", Environment.NewLine + Environment.NewLine); return targetString; } #endregion |
■ String 클래스에서 문자열을 정규화하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
using System; using System.Collections.Generic; #region 텍스트 정규화하기 - NormalizeText(sourceString) /// <summary> /// 텍스트 정규화하기 /// </summary> /// <param name="sourceString">소스 문자열</param> /// <returns>정규화 텍스트</returns> /// <remarks> /// 1. 각 줄의 문자열의 앞뒤 공백을 제거한다. /// 2. 빈줄이 반복되면 1개의 빈줄로 만든다. /// 3. 문자열이 있는 줄들 사이에 빈줄을 추가한다. /// </remarks> public string NormalizeText(string sourceString) { string[] sourceLineArray = sourceString.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); List<string> targetList = new List<string>(); bool previousLineWasEmpty = false; foreach(string sourceLine in sourceLineArray) { string targetLine = sourceLine.Trim(); if (string.IsNullOrEmpty(targetLine)) { if(!previousLineWasEmpty) { targetList.Add(string.Empty); previousLineWasEmpty = true; } } else { targetList.Add(targetLine); previousLineWasEmpty = false; } } return string.Join(Environment.NewLine, targetList); } #endregion |
■ Window 클래스에서 윈도우를 화면 앞으로 가져오는 방법을 보여준다. ▶ WindowHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; /// <summary> /// 윈도우 헬퍼 /// </summary> public static class WindowHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Import ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 활성 윈도우 설정하기 - SetForegroundWindow(windowHandle) /// <summary> /// 활성 윈도우 설정하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool SetForegroundWindow(IntPtr windowHandle); #endregion #region 윈도우 표시하기 - ShowWindow(windowHandle, command) /// <summary> /// 윈도우 표시하기 /// </summary> /// <param name="windowHandle">윈도우 핸들</param> /// <param name="commandShow">명령</param> /// <returns>처리 결과</returns> [DllImport("user32")] private static extern bool ShowWindow(IntPtr windowHandle, int command); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SW_SHOW /// </summary> private const int SW_SHOW = 5; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 윈도우 앞으로 가져오기 - BringToFront(window) /// <summary> /// 윈도우 앞으로 가져오기 /// </summary> /// <param name="window">윈도우</param> public static void BringToFront(Window window) { WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window); nint windowHandle = windowInteropHelper.Handle; ShowWindow(windowHandle, SW_SHOW); SetForegroundWindow(windowHandle); } #endregion } |
■ ManagementObjectSearcher 클래스를 사용해 NVIDIA GPU 설치 여부를 구하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
using System; using System.Management; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region NVIDIA GPU 설치 여부 구하기 - IsInstalledNvidiaGPU() /// <summary> /// NVIDIA GPU 설치 여부 구하기 /// </summary> /// <returns>NVIDIA GPU 설치 여부</returns> private static bool IsInstalledNvidiaGPU() { using ManagementObjectSearcher managementObjectSearcher = new("SELECT * FROM Win32_VideoController"); foreach(ManagementObject managementObject in managementObjectSearcher.Get()) { string name = managementObject["Name"] as string; if(!string.IsNullOrEmpty(name) && name.ToLower().Contains("nvidia")) { return true; } } return false; } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { bool isInstalledNvidiaGPU = IsInstalledNvidiaGPU(); Console.WriteLine(isInstalledNvidiaGPU ? "NVIDIA GPU가 설치되어 있습니다." : "NVIDIA GPU가 설치되어 있지 않습니다."); } #endregion } |
TestProject.zip
■ RuntimeInformation 클래스의 IsOSPlatform 정적 메소드를 사용해 윈도우즈 운영 체제가 아닌 경우 실행을 중단하는 방법을 보여준다. ▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using System; using System.Runtime.InteropServices; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { if(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Console.WriteLine("이 프로그램은 Windows에서만 실행할 수 있습니다."); return; } } #endregion } |
TestProject.zip
■ HttpClient 클래스를 사용해 Ollama 연동 파이썬 LLM 서버와 통신하는 방법을 보여준다. ▶ AdditionalKeywordArgument.cs
1 2 3 4 5 6 7 8 9 10 |
namespace TestProject; /// <summary> /// 부가적 키워드 인자 /// </summary> public class AdditionalKeywordArgument { } |
▶ AIMessageChunk.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
using Newtonsoft.Json; namespace TestProject; /// <summary> /// AI 메시지 청크 /// </summary> public class AIMessageChunk { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 컨텐트 - Content /// <summary> /// 컨텐트 /// </summary> [JsonProperty("content")] public string Content { get; set; } #endregion #region 부가적 키워드 인자 - AdditionalKeywordArgument /// <summary> /// 부가적 키워드 인자 /// </summary> [JsonProperty("additional_kwargs")] public AdditionalKeywordArgument AdditionalKeywordArgument { get; set; } #endregion #region 응답 메타 데이터 - ResponseMetadata /// <summary> /// 응답 메타 데이터 /// </summary> [JsonProperty("response_metadata")] public ResponseMetadata ResponseMetadata { get; set; } #endregion #region 타입 - Type /// <summary> /// 타입 /// </summary> [JsonProperty("type")] public string Type { get; set; } #endregion #region 명칭 - Name /// <summary> /// 명칭 /// </summary> [JsonProperty("name")] public string Name { get; set; } #endregion #region ID - ID /// <summary> /// ID /// </summary> [JsonProperty("id")] public string ID { get; set; } #endregion #region 예제 여부 - Example /// <summary> /// 예제 여부 /// </summary> [JsonProperty("example")] public bool Example { get; set; } #endregion #region 도구 호출 리스트 - ToolCallList /// <summary> /// 도구 호출 리스트 /// </summary> [JsonProperty("tool_calls")] public ToolCallList ToolCallList { get; set; } #endregion #region 무효 도구 호출 리스트 - InvalidToolCallList /// <summary> /// 무효 도구 호출 리스트 /// </summary> [JsonProperty("invalid_tool_calls")] public InvalidToolCallList InvalidToolCallList { get; set; } #endregion #region 사용 메타 데이터 - UsageMetadata /// <summary> /// 사용 메타 데이터 /// </summary> [JsonProperty("usage_metadata")] public UsageMetadata UsageMetadata { get; set; } #endregion #region 도구 호출 청크 리스트 - ToolCallChunkList /// <summary> /// 도구 호출 청크 리스트 /// </summary> [JsonProperty("tool_call_chunks")] public ToolCallChunkList ToolCallChunkList { get; set; } #endregion } |
▶ InvalidToolCallList.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
using System.Collections.Generic; namespace TestProject; /// <summary> /// 무효 도구 호출 리스트 /// </summary> public class InvalidToolCallList : List<object> { } |
▶
■ Control 클래스를 사용해 확대/축소/이동 컨트롤을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ZoomableCanvas}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ZoomableCanvas}"> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"> <Canvas Name="PART_Canvas" Width="{TemplateBinding CanvasWidth}" Height="{TemplateBinding CanvasHeight}" Background="LightGray"> </Canvas> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <local:ZoomableCanvas Margin="10" Background="LightYellow" CanvasWidth="500" CanvasHeight="400" ClipToBounds="True" /> </Window> |
▶ ZoomableCanvas.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace TestProject; /// <summary> /// 확대/축소 컨트롤 /// </summary> public class ZoomableCanvas : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 캔버스 너비 속성 - CanvasWidthProperty /// <summary> /// 캔버스 너비 속성 /// </summary> public static readonly DependencyProperty CanvasWidthProperty = DependencyProperty.Register ( "CanvasWidth", typeof(double), typeof(ZoomableCanvas), new PropertyMetadata(300.0, CanvasSizePropertyChangedCallback) ); #endregion #region 캔버스 높이 속성 - CanvasHeightProperty /// <summary> /// 캔버스 높이 속성 /// </summary> public static readonly DependencyProperty CanvasHeightProperty = DependencyProperty.Register ( "CanvasHeight", typeof(double), typeof(ZoomableCanvas), new PropertyMetadata(200.0, CanvasSizePropertyChangedCallback) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 캔버스 너비 - CanvasWidth /// <summary> /// 캔버스 너비 /// </summary> public double CanvasWidth { get => (double)GetValue(CanvasWidthProperty); set => SetValue(CanvasWidthProperty, value); } #endregion #region 캔버스 높이 - CanvasHeight /// <summary> /// 캔버스 높이 /// </summary> public double CanvasHeight { get => (double)GetValue(CanvasHeightProperty); set => SetValue(CanvasHeightProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 캔버스 /// </summary> private Canvas canvas; /// <summary> /// 스케일 변환 /// </summary> private ScaleTransform scaleTransform; /// <summary> /// 이동 변환 /// </summary> private TranslateTransform translateTransform; /// <summary> /// 시작 포인트 /// </summary> private Point startPoint; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ZoomableCanvas() /// <summary> /// 생성자 /// </summary> static ZoomableCanvas() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ZoomableCanvas), new FrameworkPropertyMetadata(typeof(ZoomableCanvas))); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 캔버스 크기 속성 변경시 콜백 처리하기 - CanvasSizePropertyChangedCallback(d, e) /// <summary> /// 캔버스 크기 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void CanvasSizePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ZoomableCanvas zoomableCanvas = d as ZoomableCanvas; if(zoomableCanvas != null && zoomableCanvas.canvas != null) { zoomableCanvas.canvas.Width = zoomableCanvas.CanvasWidth; zoomableCanvas.canvas.Height = zoomableCanvas.CanvasHeight; } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.canvas = GetTemplateChild("PART_Canvas") as Canvas; if(this.canvas != null) { this.scaleTransform = new ScaleTransform(); this.translateTransform = new TranslateTransform(); TransformGroup transformGroup = new TransformGroup(); transformGroup.Children.Add(this.scaleTransform ); transformGroup.Children.Add(this.translateTransform); this.canvas.RenderTransformOrigin = new Point(0.5, 0.5); this.canvas.RenderTransform = transformGroup; } } #endregion //////////////////////////////////////////////////////////////////////////////// Protected #region 마우스 휠 처리하기 - OnMouseWheel(e) /// <summary> /// 마우스 휠 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseWheel(MouseWheelEventArgs e) { base.OnMouseWheel(e); if(this.canvas == null) { return; } double zoom = e.Delta > 0 ? 1.1 : 0.9; Point mousePoition = e.GetPosition(this.canvas); this.scaleTransform.ScaleX *= zoom; this.scaleTransform.ScaleY *= zoom; this.translateTransform.X += (1 - zoom) * mousePoition.X; this.translateTransform.Y += (1 - zoom) * mousePoition.Y; } #endregion #region 마우스 왼쪽 버튼 DOWN 처리하기 - OnMouseLeftButtonDown(e) /// <summary> /// 마우스 왼쪽 버튼 DOWN 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); this.startPoint = e.GetPosition(this); CaptureMouse(); } #endregion #region 마우스 이동시 처리하기 - OnMouseMove(e) /// <summary> /// 마우스 이동시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if(IsMouseCaptured) { Point currentPoint = e.GetPosition(this); Vector deltaVector = currentPoint - this.startPoint; this.translateTransform.X += deltaVector.X; this.translateTransform.Y += deltaVector.Y; this.startPoint = currentPoint; } } #endregion #region 마우스 왼쪽 버튼 UP 처리하기 - OnMouseLeftButtonUp(e) /// <summary> /// 마우스 왼쪽 버튼 UP 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { base.OnMouseLeftButtonUp(e); ReleaseMouseCapture(); } #endregion } |
TestProject.zip
■ Control 클래스를 사용해 프로세스 링 컨트롤을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ProcessRing}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ProcessRing}"> <Grid Background="{TemplateBinding Background}"> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding RingWidth}" Height="{TemplateBinding RingHeight}"> <Grid Name="PART_ContainerGrid"> <Path Name="PART_BackgroundRingPath" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{TemplateBinding RingThickness}" Stroke="{TemplateBinding RingBrush}" Opacity="0.3"> <Path.Data> <PathGeometry> <PathFigure x:Name="PART_BackgroundPathFigure"> <ArcSegment x:Name="PART_BackgroundArcSegment" Point="50 0" Size="50 50" SweepDirection="Clockwise" /> </PathFigure> </PathGeometry> </Path.Data> </Path> <Path Name="PART_RingPath" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{TemplateBinding RingThickness}" Stroke="{TemplateBinding RingBrush}" RenderTransformOrigin="0.5 0.5"> <Path.Data> <PathGeometry> <PathFigure x:Name="PART_PathFigure"> <ArcSegment x:Name="PART_ArcSegment" Point="50 0" Size="50 50" SweepDirection="Clockwise" /> </PathFigure> </PathGeometry> </Path.Data> <Path.RenderTransform> <RotateTransform x:Name="PART_RotationTransform" /> </Path.RenderTransform> </Path> </Grid> </Viewbox> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <local:ProcessRing Width="150" Height="150" RingWidth="100" RingHeight="100" RingStartAngle="0" RingEndAngle="270" RingThickness="10" RingBrush="Blue" IsProcessing="True" /> </Window> |
▶ ProcessRing.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace TestProject; /// <summary> /// 프로세스 링 컨트롤 /// </summary> public class ProcessRing : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 링 너비 속성 - RingWidthProperty /// <summary> /// 링 너비 속성 /// </summary> public static readonly DependencyProperty RingWidthProperty = DependencyProperty.Register ( "RingWidth", typeof(double), typeof(ProcessRing), new PropertyMetadata(80.0) ); #endregion #region 링 높이 속성 - RingHeightProperty /// <summary> /// 링 높이 속성 /// </summary> public static readonly DependencyProperty RingHeightProperty = DependencyProperty.Register ( "RingHeight", typeof(double), typeof(ProcessRing), new PropertyMetadata(80.0) ); #endregion #region 링 시작 각도 속성 - RingStartAngleProperty /// <summary> /// 링 시작 각도 속성 /// </summary> public static readonly DependencyProperty RingStartAngleProperty = DependencyProperty.Register ( "RingStartAngle", typeof(double), typeof(ProcessRing), new PropertyMetadata(0.0, RingAnglePropertyChangedCallback) ); #endregion #region 링 종료 각도 속성 - RingEndAngleProperty /// <summary> /// 링 종료 각도 속성 /// </summary> public static readonly DependencyProperty RingEndAngleProperty = DependencyProperty.Register ( "RingEndAngle", typeof(double), typeof(ProcessRing), new PropertyMetadata(360.0, RingAnglePropertyChangedCallback) ); #endregion #region 링 두께 속성 - RingThicknessProperty /// <summary> /// 링 두께 속성 /// </summary> public static readonly DependencyProperty RingThicknessProperty = DependencyProperty.Register ( "RingThickness", typeof(double), typeof(ProcessRing), new PropertyMetadata(5.0, RingThicknessPropertyChangedCallback) ); #endregion #region 링 브러시 속성 - RingBrushProperty /// <summary> /// 링 브러시 속성 /// </summary> public static readonly DependencyProperty RingBrushProperty = DependencyProperty.Register ( "RingBrush", typeof(Brush), typeof(ProcessRing), new PropertyMetadata(Brushes.Black) ); #endregion #region 처리 여부 속성 - IsProcessingProperty /// <summary> /// 처리 여부 속성 /// </summary> public static readonly DependencyProperty IsProcessingProperty = DependencyProperty.Register ( "IsProcessing", typeof(bool), typeof(ProcessRing), new PropertyMetadata(false, IsProcessingPropertyChangedCallback) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 회전 변환 /// </summary> private RotateTransform rotateTransform; /// <summary> /// 링 패스 /// </summary> private Path ringPath; /// <summary> /// 패스 피규어 /// </summary> private PathFigure pathFigure; /// <summary> /// 아크 세그먼트 /// </summary> private ArcSegment arcSegment; /// <summary> /// 배경 링 패스 /// </summary> private Path backgroundRingPath; /// <summary> /// 배경 패스 피규어 /// </summary> private PathFigure backgroundPathFigure; /// <summary> /// 배경 아크 세그먼트 /// </summary> private ArcSegment backgroundArcSegment; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 링 너비 - RingWidth /// <summary> /// 링 너비 /// </summary> public double RingWidth { get => (double)GetValue(RingWidthProperty); set => SetValue(RingWidthProperty, value); } #endregion #region 링 높이 - RingHeight /// <summary> /// 링 높이 /// </summary> public double RingHeight { get => (double)GetValue(RingHeightProperty); set => SetValue(RingHeightProperty, value); } #endregion #region 링 시작 각도 - RingStartAngle /// <summary> /// 링 시작 각도 /// </summary> public double RingStartAngle { get => (double)GetValue(RingStartAngleProperty); set => SetValue(RingStartAngleProperty, value); } #endregion #region 링 종료 각도 - RingEndAngle /// <summary> /// 링 종료 각도 /// </summary> public double RingEndAngle { get => (double)GetValue(RingEndAngleProperty); set => SetValue(RingEndAngleProperty, value); } #endregion #region 링 두께 - RingThickness /// <summary> /// 링 두께 /// </summary> public double RingThickness { get => (double)GetValue(RingThicknessProperty); set => SetValue(RingThicknessProperty, value); } #endregion #region 링 브러시 - RingBrush /// <summary> /// 링 브러시 /// </summary> public Brush RingBrush { get => (Brush)GetValue(RingBrushProperty); set => SetValue(RingBrushProperty, value); } #endregion #region 처리 여부 - IsProcessing /// <summary> /// 처리 여부 /// </summary> public bool IsProcessing { get => (bool)GetValue(IsProcessingProperty); set => SetValue(IsProcessingProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ProcessRing() /// <summary> /// 생성자 /// </summary> static ProcessRing() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ProcessRing), new FrameworkPropertyMetadata(typeof(ProcessRing))); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ProcessRing() /// <summary> /// 생성자 /// </summary> public ProcessRing() { Width = 100; Height = 100; RingWidth = 80; RingHeight = 80; RingThickness = 5; Background = Brushes.Transparent; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 링 각도 속성 변경시 콜백 처리하기 - RingAnglePropertyChangedCallback(d, e) /// <summary> /// 링 각도 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void RingAnglePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.UpdateRing(); } #endregion #region 링 두께 속성 변경시 콜백 처리하기 - RingThicknessPropertyChangedCallback(d, e) /// <summary> /// 링 두께 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void RingThicknessPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.RingThickness = Math.Min((double)e.NewValue, Math.Min(processRing.RingWidth, processRing.RingHeight) / 2); processRing.UpdateRing(); } #endregion #region 처리 여부 속성 변경시 콜백 처리하기 - IsProcessingPropertyChangedCallback(d, e) /// <summary> /// 처리 여부 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void IsProcessingPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.UpdateAnimation(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.rotateTransform = GetTemplateChild("PART_RotationTransform" ) as RotateTransform; this.ringPath = GetTemplateChild("PART_RingPath" ) as Path; this.pathFigure = GetTemplateChild("PART_PathFigure" ) as PathFigure; this.arcSegment = GetTemplateChild("PART_ArcSegment" ) as ArcSegment; this.backgroundRingPath = GetTemplateChild("PART_BackgroundRingPath" ) as Path; this.backgroundPathFigure = GetTemplateChild("PART_BackgroundPathFigure") as PathFigure; this.backgroundArcSegment = GetTemplateChild("PART_BackgroundArcSegment") as ArcSegment; UpdateRing(); UpdateAnimation(); } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 포인트 회전하기 - RotatePoint(point, angle) /// <summary> /// 포인트 회전하기 /// </summary> /// <param name="point">포인트</param> /// <param name="angle">각도</param> /// <returns>회전 포인트</returns> private Point RotatePoint(Point point, double angle) { double radians = angle * (Math.PI / 180); return new Point ( point.X * Math.Cos(radians) - point.Y * Math.Sin(radians) + RingThickness / 2, point.X * Math.Sin(radians) + point.Y * Math.Cos(radians) + RingThickness / 2 ); } #endregion #region 링 업데이트하기 - UpdateRing() /// <summary> /// 링 업데이트하기 /// </summary> private void UpdateRing() { if(this.pathFigure != null && this.arcSegment != null) { double radius = Math.Min(RingWidth, RingHeight) / 2 - RingThickness / 2; double angleDifference = (RingEndAngle - RingStartAngle + 360) % 360; #region 링를 설정한다. Point startPoint = new(radius, 0); startPoint = RotatePoint(startPoint, RingStartAngle); this.pathFigure.StartPoint = new Point(startPoint.X + radius, startPoint.Y + radius); Point endPoint = new Point(radius, 0); endPoint = RotatePoint(endPoint, RingEndAngle); this.arcSegment.Point = new Point(endPoint.X + radius, endPoint.Y + radius); this.arcSegment.Size = new Size(radius, radius); this.arcSegment.IsLargeArc = angleDifference > 180; #endregion #region 배경 링를 설정한다. Point backgroundStartPoint = new(radius, 0d); backgroundStartPoint = RotatePoint(backgroundStartPoint, 0d); this.backgroundPathFigure.StartPoint = new Point(backgroundStartPoint.X + radius, backgroundStartPoint.Y + radius); Point backgroundEndPoint = new Point(radius, 0); backgroundEndPoint = RotatePoint(backgroundEndPoint, 359.9); this.backgroundArcSegment.Point = new Point(backgroundEndPoint.X + radius, backgroundEndPoint.Y + radius); this.backgroundArcSegment.Size = new Size(radius, radius); this.backgroundArcSegment.IsLargeArc = angleDifference > 180; #endregion } } #endregion #region 애니메이션 업데이트하기 - UpdateAnimation() /// <summary> /// 애니메이션 업데이트하기 /// </summary> private void UpdateAnimation() { if(this.rotateTransform != null && this.ringPath != null) { if(IsProcessing) { DoubleAnimation rotateAnimation = new() { RepeatBehavior = RepeatBehavior.Forever, Duration = TimeSpan.FromSeconds(2), From = 0, To = 360 }; this.rotateTransform.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation); } else { this.rotateTransform.BeginAnimation(RotateTransform.AngleProperty, null); } } } #endregion } |
■ Control 클래스를 사용해 프로세스 링 컨트롤을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ProcessRing}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ProcessRing}"> <Grid Background="{TemplateBinding Background}"> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding RingWidth}" Height="{TemplateBinding RingHeight}"> <Grid Name="PART_ContainerGrid" RenderTransformOrigin="0.5 0.5"> <Grid.RenderTransform> <RotateTransform x:Name="PART_RotationTransform" /> </Grid.RenderTransform> <Path Name="PART_RingPath" StrokeThickness="{TemplateBinding RingThickness}" Stroke="{TemplateBinding RingBrush}"> <Path.Data> <PathGeometry> <PathFigure x:Name="PART_PathFigure"> <ArcSegment x:Name="PART_ArcSegment" Point="50 0" Size="50 50" SweepDirection="Clockwise" /> </PathFigure> </PathGeometry> </Path.Data> </Path> </Grid> </Viewbox> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <local:ProcessRing Width="150" Height="150" RingWidth="100" RingHeight="100" RingStartAngle="0" RingEndAngle="330" RingThickness="10" RingBrush="Gold" IsProcessing="True" /> </Window> |
▶ ProcessRing.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace TestProject; /// <summary> /// 프로세스 링 컨트롤 /// </summary> public class ProcessRing : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 링 너비 속성 - RingWidthProperty /// <summary> /// 링 너비 속성 /// </summary> public static readonly DependencyProperty RingWidthProperty = DependencyProperty.Register ( "RingWidth", typeof(double), typeof(ProcessRing), new PropertyMetadata(80.0) ); #endregion #region 링 높이 속성 - RingHeightProperty /// <summary> /// 링 높이 속성 /// </summary> public static readonly DependencyProperty RingHeightProperty = DependencyProperty.Register ( "RingHeight", typeof(double), typeof(ProcessRing), new PropertyMetadata(80.0) ); #endregion #region 링 시작 각도 속성 - RingStartAngleProperty /// <summary> /// 링 시작 각도 속성 /// </summary> public static readonly DependencyProperty RingStartAngleProperty = DependencyProperty.Register ( "RingStartAngle", typeof(double), typeof(ProcessRing), new PropertyMetadata(0.0, RingAnglePropertyChangedCallback) ); #endregion #region 링 종료 각도 속성 - RingEndAngleProperty /// <summary> /// 링 종료 각도 속성 /// </summary> public static readonly DependencyProperty RingEndAngleProperty = DependencyProperty.Register ( "RingEndAngle", typeof(double), typeof(ProcessRing), new PropertyMetadata(360.0, RingAnglePropertyChangedCallback) ); #endregion #region 링 두께 속성 - RingThicknessProperty /// <summary> /// 링 두께 속성 /// </summary> public static readonly DependencyProperty RingThicknessProperty = DependencyProperty.Register ( "RingThickness", typeof(double), typeof(ProcessRing), new PropertyMetadata(5.0, RingThicknessPropertyChangedCallback) ); #endregion #region 링 브러시 속성 - RingBrushProperty /// <summary> /// 링 브러시 속성 /// </summary> public static readonly DependencyProperty RingBrushProperty = DependencyProperty.Register ( "RingBrush", typeof(Brush), typeof(ProcessRing), new PropertyMetadata(Brushes.Black) ); #endregion #region 처리 여부 속성 - IsProcessingProperty /// <summary> /// 처리 여부 속성 /// </summary> public static readonly DependencyProperty IsProcessingProperty = DependencyProperty.Register ( "IsProcessing", typeof(bool), typeof(ProcessRing), new PropertyMetadata(false, IsProcessingPropertyChangedCallback) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 회전 변환 /// </summary> private RotateTransform rotateTransform; /// <summary> /// 링 패스 /// </summary> private Path ringPath; /// <summary> /// 패스 피규어 /// </summary> private PathFigure pathFigure; /// <summary> /// 아크 세그먼트 /// </summary> private ArcSegment arcSegment; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 링 너비 - RingWidth /// <summary> /// 링 너비 /// </summary> public double RingWidth { get => (double)GetValue(RingWidthProperty); set => SetValue(RingWidthProperty, value); } #endregion #region 링 높이 - RingHeight /// <summary> /// 링 높이 /// </summary> public double RingHeight { get => (double)GetValue(RingHeightProperty); set => SetValue(RingHeightProperty, value); } #endregion #region 링 시작 각도 - RingStartAngle /// <summary> /// 링 시작 각도 /// </summary> public double RingStartAngle { get => (double)GetValue(RingStartAngleProperty); set => SetValue(RingStartAngleProperty, value); } #endregion #region 링 종료 각도 - RingEndAngle /// <summary> /// 링 종료 각도 /// </summary> public double RingEndAngle { get => (double)GetValue(RingEndAngleProperty); set => SetValue(RingEndAngleProperty, value); } #endregion #region 링 두께 - RingThickness /// <summary> /// 링 두께 /// </summary> public double RingThickness { get => (double)GetValue(RingThicknessProperty); set => SetValue(RingThicknessProperty, value); } #endregion #region 링 브러시 - RingBrush /// <summary> /// 링 브러시 /// </summary> public Brush RingBrush { get => (Brush)GetValue(RingBrushProperty); set => SetValue(RingBrushProperty, value); } #endregion #region 처리 여부 - IsProcessing /// <summary> /// 처리 여부 /// </summary> public bool IsProcessing { get => (bool)GetValue(IsProcessingProperty); set => SetValue(IsProcessingProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ProcessRing() /// <summary> /// 생성자 /// </summary> static ProcessRing() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ProcessRing), new FrameworkPropertyMetadata(typeof(ProcessRing))); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ProcessRing() /// <summary> /// 생성자 /// </summary> public ProcessRing() { Width = 100; Height = 100; RingWidth = 80; RingHeight = 80; RingThickness = 5; Background = Brushes.Transparent; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 링 각도 속성 변경시 콜백 처리하기 - RingAnglePropertyChangedCallback(d, e) /// <summary> /// 링 각도 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void RingAnglePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.UpdateRing(); } #endregion #region 링 두께 속성 변경시 콜백 처리하기 - RingThicknessPropertyChangedCallback(d, e) /// <summary> /// 링 두께 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void RingThicknessPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.RingThickness = Math.Min((double)e.NewValue, Math.Min(processRing.RingWidth, processRing.RingHeight) / 2); processRing.UpdateRing(); } #endregion #region 처리 여부 속성 변경시 콜백 처리하기 - IsProcessingPropertyChangedCallback(d, e) /// <summary> /// 처리 여부 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void IsProcessingPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ProcessRing processRing = d as ProcessRing; processRing.UpdateAnimation(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.rotateTransform = GetTemplateChild("PART_RotationTransform") as RotateTransform; this.ringPath = GetTemplateChild("PART_RingPath" ) as Path; this.pathFigure = GetTemplateChild("PART_PathFigure" ) as PathFigure; this.arcSegment = GetTemplateChild("PART_ArcSegment" ) as ArcSegment; UpdateRing(); UpdateAnimation(); } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 포인트 회전하기 - RotatePoint(point, angle) /// <summary> /// 포인트 회전하기 /// </summary> /// <param name="point">포인트</param> /// <param name="angle">각도</param> /// <returns>회전 포인트</returns> private Point RotatePoint(Point point, double angle) { double radians = angle * (Math.PI / 180); return new Point ( point.X * Math.Cos(radians) - point.Y * Math.Sin(radians) + RingThickness / 2, point.X * Math.Sin(radians) + point.Y * Math.Cos(radians) + RingThickness / 2 ); } #endregion #region 링 업데이트하기 - UpdateRing() /// <summary> /// 링 업데이트하기 /// </summary> private void UpdateRing() { if(this.pathFigure != null && this.arcSegment != null) { double radius = Math.Min(RingWidth, RingHeight) / 2 - RingThickness / 2; Point startPoint = new(radius, 0); startPoint = RotatePoint(startPoint, RingStartAngle); this.pathFigure.StartPoint = new Point(startPoint.X + radius, startPoint.Y + radius); Point endPoint = new Point(radius, 0); endPoint = RotatePoint(endPoint, RingEndAngle); this.arcSegment.Point = new Point(endPoint.X + radius, endPoint.Y + radius); this.arcSegment.Size = new Size(radius, radius); double angleDifference = (RingEndAngle - RingStartAngle + 360) % 360; this.arcSegment.IsLargeArc = angleDifference > 180; } } #endregion #region 애니메이션 업데이트하기 - UpdateAnimation() /// <summary> /// 애니메이션 업데이트하기 /// </summary> private void UpdateAnimation() { if(this.rotateTransform != null && this.ringPath != null) { if(IsProcessing) { DoubleAnimation rotateAnimation = new() { RepeatBehavior = RepeatBehavior.Forever, Duration = TimeSpan.FromSeconds(2), From = 0, To = 360 }; this.rotateTransform.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation); } else { this.rotateTransform.BeginAnimation(RotateTransform.AngleProperty, null); } } } #endregion } |
■ System.Drawing.Common 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ Button 클래스를 사용해 중단 버튼을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:StopButton}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="CornerRadius" Value="5" /> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="#003e92" /> <Setter Property="Background" Value="#fcfcfc" /> <Setter Property="Foreground" Value="Black" /> <Setter Property="Padding" Value="10" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:StopButton}"> <Border Name="PART_RootBorder" Padding="{TemplateBinding Padding}" CornerRadius="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CornerRadius}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal"> <Viewbox Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IconWidth}" Height="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IconHeight}"> <Path Name="PART_IconPath" Fill="#003e92" Stretch="Uniform" Data="M 0 0 H 20 V 20 H 0 Z" /> </Viewbox> <TextBlock Name="PART_ContentTextBlock" VerticalAlignment="Center" Margin="8 0 0 0" FontSize="14" Text="{TemplateBinding Content}" /> </StackPanel> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="PART_RootBorder" Property="Background" Value="#f0f0f0" /> <Setter TargetName="PART_IconPath" Property="Fill" Value="#0050b8" /> <Setter TargetName="PART_ContentTextBlock" Property="Foreground" Value="#0050b8" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="PART_RootBorder" Property="Background" Value="#e0e0e0" /> <Setter TargetName="PART_IconPath" Property="Fill" Value="#002a66" /> <Setter TargetName="PART_ContentTextBlock" Property="Foreground" Value="#002a66" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <local:StopButton HorizontalAlignment="Center" VerticalAlignment="Center" Padding="10" Content="Stop" /> </Window> |
▶ StopButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
using System.Windows; using System.Windows.Controls; namespace TestProject; /// <summary> /// 중단 버튼 /// </summary> public class StopButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 코너 반경 속성 - CornerRadiusProperty /// <summary> /// 코너 반경 속성 /// </summary> public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register ( "CornerRadius", typeof(CornerRadius), typeof(StopButton), new PropertyMetadata(new CornerRadius(5)) ); #endregion #region 아이콘 너비 속성 - IconWidthProperty /// <summary> /// 아이콘 너비 속성 /// </summary> public static readonly DependencyProperty IconWidthProperty = DependencyProperty.Register ( "IconWidth", typeof(double), typeof(StopButton), new PropertyMetadata(14.0) ); #endregion #region 아이콘 높이 속성 - IconHeightProperty /// <summary> /// 아이콘 높이 속성 /// </summary> public static readonly DependencyProperty IconHeightProperty = DependencyProperty.Register ( "IconHeight", typeof(double), typeof(StopButton), new PropertyMetadata(14.0) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 코너 반경 - CornerRadius /// <summary> /// 코너 반경 /// </summary> public CornerRadius CornerRadius { get => (CornerRadius)GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); } #endregion #region 아이콘 너비 - IconWidth /// <summary> /// 아이콘 너비 /// </summary> public double IconWidth { get => (double)GetValue(IconWidthProperty); set => SetValue(IconWidthProperty, value); } #endregion #region 아이콘 높이 - IconHeight /// <summary> /// 아이콘 높이 /// </summary> public double IconHeight { get => (double)GetValue(IconHeightProperty); set => SetValue(IconHeightProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - StopButton() /// <summary> /// 생성자 /// </summary> static StopButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(StopButton), new FrameworkPropertyMetadata(typeof(StopButton))); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - StopButton /// <summary> /// 생성자 /// </summary> public StopButton() : base() { Content = "Stop"; } #endregion } |
TestProject.zip
■ 윈도우즈 10 버전에서 윈도우즈 11 버전의 Segoe UI Variable 폰트를 사용하는 방법을 보여준다. ▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="800" Height="600" Title="TestProject"> <Window.Resources> <FontFamily x:Key="SegoeUIVariableFontFamilyKey">pack://application:,,,/FONT/#Segoe UI Variable</FontFamily> </Window.Resources> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock Name="textBlock1" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="맑은 고딕" FontWeight="Light" FontStretch="Expanded" FontSize="24" Text="맑은 고딕 : 0123456789" /> <TextBlock Name="textBlock2" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0 20 0 0" FontFamily="{StaticResource SegoeUIVariableFontFamilyKey}" FontWeight="Light" FontStretch="Expanded" FontSize="24" Text="Segoe UI Variable : 0123456789" /> </StackPanel> </Window> |
TestProject.zip
■ Control 클래스를 사용해 이미지 회전 목마 컨트롤을 만드는 방법을 보여준다. ▶ ArrowButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 화살표 버튼 /// </summary> public class ArrowButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 스트로크 두께 속성 - BackgroundEllipseStrokeThicknessProperty /// <summary> /// 배경 원 두께 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeThicknessProperty = DependencyProperty.Register ( "BackgroundEllipseStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(0)) ); #endregion #region 배경 원 스트로크 속성 - BackgroundEllipseStrokeProperty /// <summary> /// 배경 원 패스 데이터 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeProperty = DependencyProperty.Register ( "BackgroundEllipseStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 배경 원 채우기 속성 - BackgroundEllipseFillProperty /// <summary> /// 배경 원 채우기 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseFillProperty = DependencyProperty.Register ( "BackgroundEllipseFill", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 화살표 크기 속성 - ArrowSizeProperty /// <summary> /// 화살표 크기 속성 /// </summary> public static readonly DependencyProperty ArrowSizeProperty = DependencyProperty.Register ( "ArrowSize", typeof(double), typeof(ArrowButton), new PropertyMetadata(20.0) ); #endregion #region 화살표 방향 속성 - ArrowDirectionProperty /// <summary> /// 화살표 방향 속성 /// </summary> public static readonly DependencyProperty ArrowDirectionProperty = DependencyProperty.Register ( "ArrowDirection", typeof(ArrowDirection), typeof(ArrowButton), new PropertyMetadata(ArrowDirection.Left, DirectionPropertyChangedCallback) ); #endregion #region 화살표 스트로크 두께 속성 - ArrowStrokeThicknessProperty /// <summary> /// 화살표 두께 /// </summary> public static readonly DependencyProperty ArrowStrokeThicknessProperty = DependencyProperty.Register ( "ArrowStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(1)) ); #endregion #region 화살표 스트로크 속성 - ArrowStrokeProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowStrokeProperty = DependencyProperty.Register ( "ArrowStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Black) ); #endregion #region 왼쪽 화살표 패스 데이터 속성 - LeftArrowPathDataProperty /// <summary> /// 왼쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty LeftArrowPathDataProperty = DependencyProperty.Register ( "LeftArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 오른쪽 화살표 패스 데이터 속성 - RightArrowPathDataProperty /// <summary> /// 오른쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty RightArrowPathDataProperty = DependencyProperty.Register ( "RightArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 5 10 L 15 10 M 15 10 L 10 5 M 15 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 화살표 패스 데이터 속성 - ArrowPathDataProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowPathDataProperty = DependencyProperty.Register ( "ArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15") ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 채우기 - BackgroundEllipseFill /// <summary> /// 배경 원 채우기 /// </summary> public Brush BackgroundEllipseFill { get => (Brush)GetValue(BackgroundEllipseFillProperty); set => SetValue(BackgroundEllipseFillProperty, value); } #endregion #region 배경 원 스트로크 두께 - BackgroundEllipseStrokeThickness /// <summary> /// 배경 원 스트로크 두께 /// </summary> public Thickness BackgroundEllipseStrokeThickness { get => (Thickness)GetValue(BackgroundEllipseStrokeThicknessProperty); set => SetValue(BackgroundEllipseStrokeThicknessProperty, value); } #endregion #region 배경 원 스트로크 - BackgroundEllipseStroke /// <summary> /// 배경 원 스트로크 /// </summary> public Brush BackgroundEllipseStroke { get => (Brush)GetValue(BackgroundEllipseStrokeProperty); set => SetValue(BackgroundEllipseStrokeProperty, value); } #endregion #region 화살표 크기 - ArrowSize /// <summary> /// 화살표 크기 /// </summary> public double ArrowSize { get => (double)GetValue(ArrowSizeProperty); set => SetValue(ArrowSizeProperty, value); } #endregion #region 화살표 방향 - ArrowDirection /// <summary> /// 화살표 방향 /// </summary> public ArrowDirection ArrowDirection { get => (ArrowDirection)GetValue(ArrowDirectionProperty); set => SetValue(ArrowDirectionProperty, value); } #endregion #region 화살표 스트로크 두께 - ArrowStrokeThickness /// <summary> /// 화살표 스트로크 두께 /// </summary> public Thickness ArrowStrokeThickness { get => (Thickness)GetValue(ArrowStrokeThicknessProperty); set => SetValue(ArrowStrokeThicknessProperty, value); } #endregion #region 화살표 스트로크 - ArrowStroke /// <summary> /// 화살표 스트로크 /// </summary> public Brush ArrowStroke { get => (Brush)GetValue(ArrowStrokeProperty); set => SetValue(ArrowStrokeProperty, value); } #endregion #region 왼쪽 화살표 패스 데이터 - LeftArrowPathData /// <summary> /// 왼쪽 화살표 패스 데이터 /// </summary> public string LeftArrowPathData { get => (string)GetValue(LeftArrowPathDataProperty); set => SetValue(LeftArrowPathDataProperty, value); } #endregion #region 오른쪽 화살표 패스 데이터 - RightArrowPathData /// <summary> /// 오른쪽 화살표 패스 데이터 /// </summary> public string RightArrowPathData { get => (string)GetValue(RightArrowPathDataProperty); set => SetValue(RightArrowPathDataProperty, value); } #endregion #region 화살표 패스 데이터 - ArrowPathData /// <summary> /// 화살표 패스 데이터 /// </summary> public string ArrowPathData { get => (string)GetValue(ArrowPathDataProperty); private set => SetValue(ArrowPathDataProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ArrowButton() /// <summary> /// 생성자 /// </summary> static ArrowButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ArrowButton), new FrameworkPropertyMetadata(typeof(ArrowButton))); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 방향 속성 변경시 콜백 처리하기 - DirectionPropertyChangedCallback(d, e) /// <summary> /// 방향 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void DirectionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion #region 화살표 패스 데이터 속성 변경시 콜백 처리하기 - ArrowPathDataPropertyChangedCallback(d, e) /// <summary> /// 화살표 패스 데이터 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void ArrowPathDataPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region 화살표 패스 데이터 업데이트하기 - UpdateArrowPathData() /// <summary> /// 화살표 패스 데이터 업데이트하기 /// </summary> private void UpdateArrowPathData() { ArrowPathData = ArrowDirection == ArrowDirection.Left ? LeftArrowPathData : RightArrowPathData; } #endregion } |
▶ ArrowDirection.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
namespace TestProject; /// <summary> /// 화살표 방향 /// </summary> public enum ArrowDirection { Left, Right } |
▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ArrowButton}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ArrowButton}"> <Grid Name="grid"> <Ellipse Name="backgroundEllipse" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStroke}" Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseFill}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding ArrowSize}" Height="{TemplateBinding ArrowSize}" Margin="{TemplateBinding Padding}"> <Canvas Width="20" Height="20"> <Path Name="arrowPath" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStroke}" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Data="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowPathData}" /> </Canvas> </Viewbox> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#e0e0e0" /> <Setter TargetName="arrowPath" Property="Stroke" Value="Black" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#bdbdbd" /> <Setter TargetName="grid" Property="RenderTransform"> <Setter.Value> <TranslateTransform X="1" Y="1" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Width" Value="32" /> <Setter Property="Height" Value="32" /> <Setter Property="ArrowSize" Value="20" /> </Style> <Style TargetType="{x:Type local:ImageCarousel}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ImageCarousel}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="10" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="10" /> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <local:ArrowButton x:Name="PART_LeftArrowButton" Grid.Column="0" Width="32" Height="32" ArrowDirection="Left" ArrowSize="20" ArrowStrokeThickness="2" ArrowStroke="DarkGray" /> <Canvas Name="PART_ItemCanvas" Grid.Column="2" ClipToBounds="True" /> <local:ArrowButton x:Name="PART_RightArrowButton" Grid.Column="4" Width="32" Height="32" ArrowDirection="Right" ArrowSize="20" ArrowStrokeThickness="2" ArrowStroke="DarkGray" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ ImageCarousel.cs
■ Button 클래스를 사용해 이미지 버튼을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ImageButton}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ImageButton}"> <Border Name="PART_Border" Background="Transparent"> <Grid> <Image Name="PART_IconImage" HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding ImageWidth}" Height="{TemplateBinding ImageHeight}" Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=EnabledImageSource}" /> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="PART_IconImage" Property="RenderTransform"> <Setter.Value> <ScaleTransform ScaleX="0.9" ScaleY="0.9" /> </Setter.Value> </Setter> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter TargetName="PART_IconImage" Property="Source" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisabledImageSource}" /> <Setter Property="Opacity" Value="0.5" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ ImageButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 이미지 버튼 /// </summary> public class ImageButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Statc //////////////////////////////////////////////////////////////////////////////// Statc #region 이미지 너비 속성 - ImageWidthProperty /// <summary> /// 이미지 너비 속성 /// </summary> public static readonly DependencyProperty ImageWidthProperty = DependencyProperty.Register ( "ImageWidth", typeof(double), typeof(ImageButton), new PropertyMetadata(32.0) ); #endregion #region 이미지 높이 속성 - ImageHeightProperty /// <summary> /// 이미지 높이 속성 /// </summary> public static readonly DependencyProperty ImageHeightProperty = DependencyProperty.Register ( "ImageHeight", typeof(double), typeof(ImageButton), new PropertyMetadata(32.0) ); #endregion #region 이용 가능 이미지 소스 속성 - EnabledImageSourceProperty /// <summary> /// 이용 가능 이미지 소스 속성 /// </summary> public static readonly DependencyProperty EnabledImageSourceProperty = DependencyProperty.Register ( "EnabledImageSource", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(null) ); #endregion #region 이용 불가 이미지 소스 속성 - DisabledImageSourceProperty /// <summary> /// 이용 불가 이미지 소스 속성 /// </summary> public static readonly DependencyProperty DisabledImageSourceProperty = DependencyProperty.Register ( "DisabledImageSource", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(null) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 이미지 너비 - ImageWidth /// <summary> /// 이미지 너비 /// </summary> public double ImageWidth { get => (double)GetValue(ImageWidthProperty); set => SetValue(ImageWidthProperty, value); } #endregion #region 이미지 높이 - ImageHeight /// <summary> /// 이미지 높이 /// </summary> public double ImageHeight { get => (double)GetValue(ImageHeightProperty); set => SetValue(ImageHeightProperty, value); } #endregion #region 이용 가능 이미지 소스 - EnabledImageSource /// <summary> /// 이용 가능 이미지 소스 /// </summary> public ImageSource EnabledImageSource { get => (ImageSource)GetValue(EnabledImageSourceProperty); set => SetValue(EnabledImageSourceProperty, value); } #endregion #region 이용 불가 이미지 소스 - DisabledImageSource /// <summary> /// 이용 불가 이미지 소스 /// </summary> public ImageSource DisabledImageSource { get => (ImageSource)GetValue(DisabledImageSourceProperty); set => SetValue(DisabledImageSourceProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Statc #region 생성자 - ImageButton /// <summary> /// 생성자 /// </summary> static ImageButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ImageButton), new FrameworkPropertyMetadata(typeof(ImageButton))); } #endregion } |
▶ MainApplication.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <local:ImageButton x:Name="imageButton1" Width="40" Height="40" ImageWidth="40" ImageHeight="40" EnabledImageSource="IMAGE/new_chat.png" DisabledImageSource="IMAGE/new_chat_gray.png" /> <local:ImageButton x:Name="imageButton2" Margin="0 20 0 0" Width="20" Height="20" ImageWidth="18" ImageHeight="18" EnabledImageSource="IMAGE/send.png" DisabledImageSource="IMAGE/send_gray.png" /> <Button Name="toggleButton" Margin="0 30 0 0" Padding="10" Content="IsEnabled 속성 토글" /> </StackPanel> </Window> |
▶
■ Control 클래스를 사용해 이미지 회전 목마 컨트롤을 만드는 방법을 보여준다. ▶ ArrowButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 화살표 버튼 /// </summary> public class ArrowButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 스트로크 두께 속성 - BackgroundEllipseStrokeThicknessProperty /// <summary> /// 배경 원 두께 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeThicknessProperty = DependencyProperty.Register ( "BackgroundEllipseStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(0)) ); #endregion #region 배경 원 스트로크 속성 - BackgroundEllipseStrokeProperty /// <summary> /// 배경 원 패스 데이터 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeProperty = DependencyProperty.Register ( "BackgroundEllipseStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 배경 원 채우기 속성 - BackgroundEllipseFillProperty /// <summary> /// 배경 원 채우기 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseFillProperty = DependencyProperty.Register ( "BackgroundEllipseFill", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 화살표 크기 속성 - ArrowSizeProperty /// <summary> /// 화살표 크기 속성 /// </summary> public static readonly DependencyProperty ArrowSizeProperty = DependencyProperty.Register ( "ArrowSize", typeof(double), typeof(ArrowButton), new PropertyMetadata(20.0) ); #endregion #region 화살표 방향 속성 - ArrowDirectionProperty /// <summary> /// 화살표 방향 속성 /// </summary> public static readonly DependencyProperty ArrowDirectionProperty = DependencyProperty.Register ( "ArrowDirection", typeof(ArrowDirection), typeof(ArrowButton), new PropertyMetadata(ArrowDirection.Left, DirectionPropertyChangedCallback) ); #endregion #region 화살표 스트로크 두께 속성 - ArrowStrokeThicknessProperty /// <summary> /// 화살표 두께 /// </summary> public static readonly DependencyProperty ArrowStrokeThicknessProperty = DependencyProperty.Register ( "ArrowStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(1)) ); #endregion #region 화살표 스트로크 속성 - ArrowStrokeProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowStrokeProperty = DependencyProperty.Register ( "ArrowStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Black) ); #endregion #region 왼쪽 화살표 패스 데이터 속성 - LeftArrowPathDataProperty /// <summary> /// 왼쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty LeftArrowPathDataProperty = DependencyProperty.Register ( "LeftArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 오른쪽 화살표 패스 데이터 속성 - RightArrowPathDataProperty /// <summary> /// 오른쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty RightArrowPathDataProperty = DependencyProperty.Register ( "RightArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 5 10 L 15 10 M 15 10 L 10 5 M 15 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 화살표 패스 데이터 속성 - ArrowPathDataProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowPathDataProperty = DependencyProperty.Register ( "ArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15") ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 채우기 - BackgroundEllipseFill /// <summary> /// 배경 원 채우기 /// </summary> public Brush BackgroundEllipseFill { get => (Brush)GetValue(BackgroundEllipseFillProperty); set => SetValue(BackgroundEllipseFillProperty, value); } #endregion #region 배경 원 스트로크 두께 - BackgroundEllipseStrokeThickness /// <summary> /// 배경 원 스트로크 두께 /// </summary> public Thickness BackgroundEllipseStrokeThickness { get => (Thickness)GetValue(BackgroundEllipseStrokeThicknessProperty); set => SetValue(BackgroundEllipseStrokeThicknessProperty, value); } #endregion #region 배경 원 스트로크 - BackgroundEllipseStroke /// <summary> /// 배경 원 스트로크 /// </summary> public Brush BackgroundEllipseStroke { get => (Brush)GetValue(BackgroundEllipseStrokeProperty); set => SetValue(BackgroundEllipseStrokeProperty, value); } #endregion #region 화살표 크기 - ArrowSize /// <summary> /// 화살표 크기 /// </summary> public double ArrowSize { get => (double)GetValue(ArrowSizeProperty); set => SetValue(ArrowSizeProperty, value); } #endregion #region 화살표 방향 - ArrowDirection /// <summary> /// 화살표 방향 /// </summary> public ArrowDirection ArrowDirection { get => (ArrowDirection)GetValue(ArrowDirectionProperty); set => SetValue(ArrowDirectionProperty, value); } #endregion #region 화살표 스트로크 두께 - ArrowStrokeThickness /// <summary> /// 화살표 스트로크 두께 /// </summary> public Thickness ArrowStrokeThickness { get => (Thickness)GetValue(ArrowStrokeThicknessProperty); set => SetValue(ArrowStrokeThicknessProperty, value); } #endregion #region 화살표 스트로크 - ArrowStroke /// <summary> /// 화살표 스트로크 /// </summary> public Brush ArrowStroke { get => (Brush)GetValue(ArrowStrokeProperty); set => SetValue(ArrowStrokeProperty, value); } #endregion #region 왼쪽 화살표 패스 데이터 - LeftArrowPathData /// <summary> /// 왼쪽 화살표 패스 데이터 /// </summary> public string LeftArrowPathData { get => (string)GetValue(LeftArrowPathDataProperty); set => SetValue(LeftArrowPathDataProperty, value); } #endregion #region 오른쪽 화살표 패스 데이터 - RightArrowPathData /// <summary> /// 오른쪽 화살표 패스 데이터 /// </summary> public string RightArrowPathData { get => (string)GetValue(RightArrowPathDataProperty); set => SetValue(RightArrowPathDataProperty, value); } #endregion #region 화살표 패스 데이터 - ArrowPathData /// <summary> /// 화살표 패스 데이터 /// </summary> public string ArrowPathData { get => (string)GetValue(ArrowPathDataProperty); private set => SetValue(ArrowPathDataProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ArrowButton() /// <summary> /// 생성자 /// </summary> static ArrowButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ArrowButton), new FrameworkPropertyMetadata(typeof(ArrowButton))); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 방향 속성 변경시 콜백 처리하기 - DirectionPropertyChangedCallback(d, e) /// <summary> /// 방향 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void DirectionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion #region 화살표 패스 데이터 속성 변경시 콜백 처리하기 - ArrowPathDataPropertyChangedCallback(d, e) /// <summary> /// 화살표 패스 데이터 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void ArrowPathDataPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region 화살표 패스 데이터 업데이트하기 - UpdateArrowPathData() /// <summary> /// 화살표 패스 데이터 업데이트하기 /// </summary> private void UpdateArrowPathData() { ArrowPathData = ArrowDirection == ArrowDirection.Left ? LeftArrowPathData : RightArrowPathData; } #endregion } |
▶ ArrowDirection.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
namespace TestProject; /// <summary> /// 화살표 방향 /// </summary> public enum ArrowDirection { Left, Right } |
▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ArrowButton}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ArrowButton}"> <Grid Name="grid"> <Ellipse Name="backgroundEllipse" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStroke}" Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseFill}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding ArrowSize}" Height="{TemplateBinding ArrowSize}" Margin="{TemplateBinding Padding}"> <Canvas Width="20" Height="20"> <Path Name="arrowPath" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStroke}" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Data="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowPathData}" /> </Canvas> </Viewbox> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#e0e0e0" /> <Setter TargetName="arrowPath" Property="Stroke" Value="Black" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#bdbdbd" /> <Setter TargetName="grid" Property="RenderTransform"> <Setter.Value> <TranslateTransform X="1" Y="1" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Width" Value="32" /> <Setter Property="Height" Value="32" /> <Setter Property="ArrowSize" Value="20" /> </Style> <Style TargetType="{x:Type local:RoundImage}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:RoundImage}"> <Border Name="PART_RootBorder" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="{TemplateBinding CornerRadius}" Background="{TemplateBinding Background}"> <ContentPresenter /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="{x:Type local:ImageCarousel}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ImageCarousel}"> <Border CornerRadius="10" Background="{TemplateBinding Background}"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="10" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="5" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="5" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <local:ArrowButton x:Name="PART_PreviousArrowButton" Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Left" Width="32" Height="32" BackgroundEllipseStrokeThickness="1" BackgroundEllipseStroke="LightGray" ArrowDirection="Left" ArrowSize="20" ArrowStrokeThickness="2" ArrowStroke="Black" LeftArrowPathData="M 7 10 L 12 5 M 7 10 L 12 15" RightArrowPathData="M 13 10 L 8 5 M 13 10 L 8 15"> <local:ArrowButton.BackgroundEllipseFill> <SolidColorBrush> <SolidColorBrush.Color> <Color A="127" R="255" G="255" B="255" /> </SolidColorBrush.Color> </SolidColorBrush> </local:ArrowButton.BackgroundEllipseFill> </local:ArrowButton> <local:RoundImage x:Name="PART_RoundImage" Grid.Row="0" Grid.Column="2" Margin="0 0 0 15"> </local:RoundImage> <Border Grid.Row="0" Grid.RowSpan="2" Grid.Column="2" Margin="10" VerticalAlignment="Bottom" CornerRadius="10" BorderThickness="1" BorderBrush="DarkGray" Background="#e0ffffff" Padding="10"> <TextBlock Name="PART_DescriptionTextBlock" HorizontalAlignment="Center" Foreground="Black" TextWrapping="Wrap" /> </Border> <local:ArrowButton x:Name="PART_NextArrowButton" Grid.Row="0" Grid.RowSpan="2" Grid.Column="4" VerticalAlignment="Center" HorizontalAlignment="Right" Width="32" Height="32" BackgroundEllipseStrokeThickness="1" BackgroundEllipseStroke="LightGray" ArrowDirection="Right" ArrowSize="20" ArrowStrokeThickness="2" ArrowStroke="Black" LeftArrowPathData="M 7 10 L 12 5 M 7 10 L 12 15" RightArrowPathData="M 13 10 L 8 5 M 13 10 L 8 15"> <local:ArrowButton.BackgroundEllipseFill> <SolidColorBrush> <SolidColorBrush.Color> <Color A="192" R="255" G="255" B="255" /> </SolidColorBrush.Color> </SolidColorBrush> </local:ArrowButton.BackgroundEllipseFill> </local:ArrowButton> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ ImageCarousel.cs
■ Control 클래스를 사용해 라운드 이미지 컨트롤을 만드는 방법을 보여준다. ▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:RoundImage}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:RoundImage}"> <Border Name="PART_RootBorder" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="{TemplateBinding CornerRadius}" Background="{TemplateBinding Background}"> <ContentPresenter /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
▶ RoundImage.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 라운드 이미지 /// </summary> public class RoundImage : Control { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 코너 반경 속성 - CornerRadiusProperty /// <summary> /// 코너 반경 속성 /// </summary> public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register ( "CornerRadius", typeof(CornerRadius), typeof(RoundImage), new PropertyMetadata(new CornerRadius(10)) ); #endregion #region 스트레치 속성 - StretchProperty /// <summary> /// 스트레치 속성 /// </summary> public static readonly DependencyProperty StretchProperty = DependencyProperty.Register ( "Stretch", typeof(Stretch), typeof(RoundImage), new PropertyMetadata(Stretch.UniformToFill, StretchPropertyChangedCallback) ); #endregion #region 이미지 소스 속성 - ImageSourceProperty /// <summary> /// 이미지 소스 속성 /// </summary> public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register ( "ImageSource", typeof(ImageSource), typeof(RoundImage), new PropertyMetadata(null, ImageSourcePropertyChangedCallback) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 루트 테두리 /// </summary> private Border rootBorder = null; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 코너 반경 - CornerRadius /// <summary> /// 코너 반경 /// </summary> public CornerRadius CornerRadius { get => (CornerRadius)GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); } #endregion #region 스트레치 - Stretch /// <summary> /// 스트레치 /// </summary> public Stretch Stretch { get => (Stretch)GetValue(StretchProperty); set => SetValue(StretchProperty, value); } #endregion #region 이미지 소스 - ImageSource /// <summary> /// 이미지 소스 /// </summary> public ImageSource ImageSource { get => (ImageSource)GetValue(ImageSourceProperty); set => SetValue(ImageSourceProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - RoundImage() /// <summary> /// 생성자 /// </summary> static RoundImage() { DefaultStyleKeyProperty.OverrideMetadata(typeof(RoundImage), new FrameworkPropertyMetadata(typeof(RoundImage))); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - RoundImage() /// <summary> /// 생성자 /// </summary> public RoundImage() { Loaded += Control_Loaded; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static #region 스트레치 속성 변경시 콜백 처리하기 - StretchPropertyChangedCallback(d, e) /// <summary> /// 스트레치 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void StretchPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is RoundImage roundImage) { roundImage.UpdateBackground(); } } #endregion #region 이미지 소스 속성 변경시 콜백 처리하기 - ImageSourcePropertyChangedCallback(d, e) /// <summary> /// 이미지 소스 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void ImageSourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is RoundImage roundImage) { roundImage.UpdateBackground(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public ////////////////////////////////////////////////////////////////////// Function #region 템플리트 적용시 처리하기 - OnApplyTemplate() /// <summary> /// 템플리트 적용시 처리하기 /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.rootBorder = GetTemplateChild("PART_RootBorder") as Border; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 컨트롤 로드시 처리하기 - Control_Loaded(sender, e) /// <summary> /// 컨트롤 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Control_Loaded(object sender, RoutedEventArgs e) { UpdateBackground(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 배경 업데이트하기 - UpdateBackground() /// <summary> /// 배경 업데이트하기 /// </summary> private void UpdateBackground() { if(this.rootBorder == null) { return; } if(ImageSource != null) { this.rootBorder.Background = new ImageBrush { ImageSource = this.ImageSource, Stretch = this.Stretch }; } else { this.rootBorder.Background = null; } } #endregion } |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="CONTROL/ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="TestProject" FontFamily="나눔고딕코딩" FontSize="16"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <local:RoundImage x:Name="roundImage1" BorderThickness="3" BorderBrush="DarkGray" Width="300" Height="200" CornerRadius="20" ImageSource="IMAGE/image1.jpg"> </local:RoundImage> <local:RoundImage x:Name="roundImage2" Margin="0 10 0 0" BorderThickness="3" BorderBrush="DarkGray" Width="300" Height="200" CornerRadius="20"> </local:RoundImage> </StackPanel> </Window> |
■ Button 클래스를 사용해 화살표 원 버튼을 만드는 방법을 보여준다. ▶ ArrowButton.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject; /// <summary> /// 화살표 버튼 /// </summary> public class ArrowButton : Button { //////////////////////////////////////////////////////////////////////////////////////////////////// Dependency Property ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 스트로크 두께 속성 - BackgroundEllipseStrokeThicknessProperty /// <summary> /// 배경 원 두께 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeThicknessProperty = DependencyProperty.Register ( "BackgroundEllipseStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(0)) ); #endregion #region 배경 원 스트로크 속성 - BackgroundEllipseStrokeProperty /// <summary> /// 배경 원 패스 데이터 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseStrokeProperty = DependencyProperty.Register ( "BackgroundEllipseStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 배경 원 채우기 속성 - BackgroundEllipseFillProperty /// <summary> /// 배경 원 채우기 속성 /// </summary> public static readonly DependencyProperty BackgroundEllipseFillProperty = DependencyProperty.Register ( "BackgroundEllipseFill", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Transparent) ); #endregion #region 화살표 크기 속성 - ArrowSizeProperty /// <summary> /// 화살표 크기 속성 /// </summary> public static readonly DependencyProperty ArrowSizeProperty = DependencyProperty.Register ( "ArrowSize", typeof(double), typeof(ArrowButton), new PropertyMetadata(20.0) ); #endregion #region 화살표 방향 속성 - ArrowDirectionProperty /// <summary> /// 화살표 방향 속성 /// </summary> public static readonly DependencyProperty ArrowDirectionProperty = DependencyProperty.Register ( "ArrowDirection", typeof(ArrowDirection), typeof(ArrowButton), new PropertyMetadata(ArrowDirection.Left, DirectionPropertyChangedCallback) ); #endregion #region 화살표 스트로크 두께 속성 - ArrowStrokeThicknessProperty /// <summary> /// 화살표 두께 /// </summary> public static readonly DependencyProperty ArrowStrokeThicknessProperty = DependencyProperty.Register ( "ArrowStrokeThickness", typeof(Thickness), typeof(ArrowButton), new PropertyMetadata(new Thickness(1)) ); #endregion #region 화살표 스트로크 속성 - ArrowStrokeProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowStrokeProperty = DependencyProperty.Register ( "ArrowStroke", typeof(Brush), typeof(ArrowButton), new PropertyMetadata(Brushes.Black) ); #endregion #region 왼쪽 화살표 패스 데이터 속성 - LeftArrowPathDataProperty /// <summary> /// 왼쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty LeftArrowPathDataProperty = DependencyProperty.Register ( "LeftArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 오른쪽 화살표 패스 데이터 속성 - RightArrowPathDataProperty /// <summary> /// 오른쪽 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty RightArrowPathDataProperty = DependencyProperty.Register ( "RightArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 5 10 L 15 10 M 15 10 L 10 5 M 15 10 L 10 15", ArrowPathDataPropertyChangedCallback) ); #endregion #region 화살표 패스 데이터 속성 - ArrowPathDataProperty /// <summary> /// 화살표 패스 데이터 속성 /// </summary> public static readonly DependencyProperty ArrowPathDataProperty = DependencyProperty.Register ( "ArrowPathData", typeof(string), typeof(ArrowButton), new PropertyMetadata("M 15 10 L 5 10 M 5 10 L 10 5 M 5 10 L 10 15") ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 배경 원 채우기 - BackgroundEllipseFill /// <summary> /// 배경 원 채우기 /// </summary> public Brush BackgroundEllipseFill { get => (Brush)GetValue(BackgroundEllipseFillProperty); set => SetValue(BackgroundEllipseFillProperty, value); } #endregion #region 배경 원 스트로크 두께 - BackgroundEllipseStrokeThickness /// <summary> /// 배경 원 스트로크 두께 /// </summary> public Thickness BackgroundEllipseStrokeThickness { get => (Thickness)GetValue(BackgroundEllipseStrokeThicknessProperty); set => SetValue(BackgroundEllipseStrokeThicknessProperty, value); } #endregion #region 배경 원 스트로크 - BackgroundEllipseStroke /// <summary> /// 배경 원 스트로크 /// </summary> public Brush BackgroundEllipseStroke { get => (Brush)GetValue(BackgroundEllipseStrokeProperty); set => SetValue(BackgroundEllipseStrokeProperty, value); } #endregion #region 화살표 크기 - ArrowSize /// <summary> /// 화살표 크기 /// </summary> public double ArrowSize { get => (double)GetValue(ArrowSizeProperty); set => SetValue(ArrowSizeProperty, value); } #endregion #region 화살표 방향 - ArrowDirection /// <summary> /// 화살표 방향 /// </summary> public ArrowDirection ArrowDirection { get => (ArrowDirection)GetValue(ArrowDirectionProperty); set => SetValue(ArrowDirectionProperty, value); } #endregion #region 화살표 스트로크 두께 - ArrowStrokeThickness /// <summary> /// 화살표 스트로크 두께 /// </summary> public Thickness ArrowStrokeThickness { get => (Thickness)GetValue(ArrowStrokeThicknessProperty); set => SetValue(ArrowStrokeThicknessProperty, value); } #endregion #region 화살표 스트로크 - ArrowStroke /// <summary> /// 화살표 스트로크 /// </summary> public Brush ArrowStroke { get => (Brush)GetValue(ArrowStrokeProperty); set => SetValue(ArrowStrokeProperty, value); } #endregion #region 왼쪽 화살표 패스 데이터 - LeftArrowPathData /// <summary> /// 왼쪽 화살표 패스 데이터 /// </summary> public string LeftArrowPathData { get => (string)GetValue(LeftArrowPathDataProperty); set => SetValue(LeftArrowPathDataProperty, value); } #endregion #region 오른쪽 화살표 패스 데이터 - RightArrowPathData /// <summary> /// 오른쪽 화살표 패스 데이터 /// </summary> public string RightArrowPathData { get => (string)GetValue(RightArrowPathDataProperty); set => SetValue(RightArrowPathDataProperty, value); } #endregion #region 화살표 패스 데이터 - ArrowPathData /// <summary> /// 화살표 패스 데이터 /// </summary> public string ArrowPathData { get => (string)GetValue(ArrowPathDataProperty); private set => SetValue(ArrowPathDataProperty, value); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - ArrowButton() /// <summary> /// 생성자 /// </summary> static ArrowButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ArrowButton), new FrameworkPropertyMetadata(typeof(ArrowButton))); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 방향 속성 변경시 콜백 처리하기 - DirectionPropertyChangedCallback(d, e) /// <summary> /// 방향 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void DirectionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion #region 화살표 패스 데이터 속성 변경시 콜백 처리하기 - ArrowPathDataPropertyChangedCallback(d, e) /// <summary> /// 화살표 패스 데이터 속성 변경시 콜백 처리하기 /// </summary> /// <param name="d">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private static void ArrowPathDataPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is ArrowButton button) { button.UpdateArrowPathData(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region 화살표 패스 데이터 업데이트하기 - UpdateArrowPathData() /// <summary> /// 화살표 패스 데이터 업데이트하기 /// </summary> private void UpdateArrowPathData() { ArrowPathData = ArrowDirection == ArrowDirection.Left ? LeftArrowPathData : RightArrowPathData; } #endregion } |
▶ ArrowDirection.cs
1 2 3 4 5 6 7 8 9 10 11 12 |
namespace TestProject; /// <summary> /// 화살표 방향 /// </summary> public enum ArrowDirection { Left, Right } |
▶ ControlDictionary.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject"> <Style TargetType="{x:Type local:ArrowButton}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:ArrowButton}"> <Grid Name="grid"> <Ellipse Name="backgroundEllipse" HorizontalAlignment="Center" VerticalAlignment="Center" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseStroke}" Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=BackgroundEllipseFill}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/> <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding ArrowSize}" Height="{TemplateBinding ArrowSize}" Margin="{TemplateBinding Padding}"> <Canvas Width="20" Height="20"> <Path Name="arrowPath" StrokeThickness="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStrokeThickness}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowStroke}" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Data="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ArrowPathData}" /> </Canvas> </Viewbox> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#e0e0e0" /> <Setter TargetName="arrowPath" Property="Stroke" Value="Black" /> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="backgroundEllipse" Property="Fill" Value="#bdbdbd" /> <Setter TargetName="grid" Property="RenderTransform"> <Setter.Value> <TranslateTransform X="1" Y="1" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Width" Value="32" /> <Setter Property="Height" Value="32" /> <Setter Property="ArrowSize" Value="20" /> </Style> </ResourceDictionary> |
▶ MainApplication.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<Application x:Class="TestProject.MainApplication" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ControlDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> |