[C#] 윈도우 OS 정보 얻기

CSharp
OperatingSystem os = System.Environment.OSVersion; Console.WriteLine("플랫폼 : " + os.Platform); Console.WriteLine("서비스팩 : " + os.ServicePack); Console.WriteLine("버전 : " + os.Version); Console.WriteLine("버전 : " + os.Version); Console.WriteLine("버전 문자열 : " + os.VersionString); Console.WriteLine("CLR버전 : " + System.Environment.Version); Console.ReadLine(); // 콘솔에서 확인할수 있도록 잠시 멈춤 사용자의 정보를 획득해야 될 일이 있을 경우에 위 기능을 사용해서 처리 할 수 있습니다.
Read More

[C#] Picturebox를 투명하게

CSharp
LicenseLabel.Parent = pictureBox1; LicenseLabel.BackColor = Color.Transparent; LicenseLabel.BringToFront(); LicenseLabel.BackColor = Color.Transparent; LicenseLabel.Width = this.Width; LicenseLabel.Left = 0; LicenseLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; LicenseLabel.Parent = pictureBox1;
Read More

[C#] WebBrowser version 변경

CSharp
Program.cs 에서 다음을 사용하도록 합니다. using System.Runtime.InteropServices; using Microsoft.Win32; 레지스트리에 세팅하고 값이 정상적인지 체크하도록 하는 함수 입니다. private static void SetIEVersioneKeyforWebBrowserControl(string appName, int ieval) { string RegKeyPath = ""; RegistryKey Regkey = null; try { // x86, x64 구분 if (Environment.Is64BitProcess) { RegKeyPath = @"SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION"; } else { RegKeyPath = @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION"; } // try { Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(RegKeyPath, true); } catch (Exception ex) { Console.WriteLine(" 관리자 권한이 아니여서 접근이 불가능 합니다."); } finally { // 레지스트리의 값을 체크 if (Regkey == null) { // 찾지 못할 경우 그냥 PASS } else { // 실행 프로세스가 등록되어 있는지 값을 가져오기 string FindAppkey = Convert.ToString(Regkey.GetValue(appName)); // 이미 세팅 되어 있을 경우 if (FindAppkey == ieval.ToString()) { Regkey.Close(); } else { // 값 세팅하기 Regkey.SetValue(appName, unchecked((int)ieval), RegistryValueKind.DWord); //check for the key…
Read More

[C#] 폰트 설치 여부 체크해서 설정 도와주기

CSharp
class FontLibraryClass { public class FontLibrary { private string FontsFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Fonts); private static FontLibrary inst = new FontLibrary(); public PrivateFontCollection privateFont = new PrivateFontCollection(); /// <summary> /// /// </summary> public static FontFamily[] Families { get { return inst.privateFont.Families; } } /// <summary> /// /// </summary> public FontLibrary() { AddFontFromNanumgothic(); } /// <summary> /// 리소스에 포함된 폰트 파일을 로딩 /// </summary> private void AddFontFromMemory() { /* List<byte[]> fonts = new List<byte[]>(); fonts.Add(Properties.Resources.NanumGothic); fonts.Add(Properties.Resources.NanumGothicBold); foreach (byte[] FontData in fonts) { IntPtr fontBuffer = Marshal.AllocCoTaskMem(FontData.Length); Marshal.Copy(FontData, 0, fontBuffer, FontData.Length); privateFont.AddMemoryFont(fontBuffer, FontData.Length); } */ } /// <summary> /// 폰트 파일을 추가함. /// </summary> private void AddFontFromNanumgothic() { privateFont.AddFontFile(FontsFolder + @"\\NANUMGOTHIC.TTF"); } } /// <summary> /// 폰트 존재 여부 체크 /// </summary> public void FontInstallCheck() { bool FontInstallBoolNanum = false; // FontFamily[] fonts =…
Read More
[C#] 관리자 권한으로 실행하기

[C#] 관리자 권한으로 실행하기

CSharp
해당 작업은 Program.cs 에서 작업을 합니다. using System.Security.Principal; using System.Diagnostics; /// <summary> /// 관리자 권한 체크 /// </summary> /// <returns></returns> public static bool IsAdministrator() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); if (null != identity) { WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } return false; } 메인 실행전에 관리자 권한으로 실행 하도록 하면 됩니다. [STAThread] static void Main() { if (IsAdministrator() == false) { try { ProcessStartInfo procInfo = new ProcessStartInfo(); procInfo.UseShellExecute = true; procInfo.FileName = Application.ExecutablePath; procInfo.WorkingDirectory = Environment.CurrentDirectory; procInfo.Verb = "runas"; Process.Start(procInfo); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } 위 방법으로로 처리 할 수 있지만 다른 방법도 있습니다. 프로그램  속성에서 보안의 "ClickOnce"를 선택합니다. 그러면은 위 처럼 "app.mainfest"가 생기게 됩니다. ※ 이방법을 할 경우에는 프로그램에 아이콘에 방패 모양이 생기게 됩니다. 원래 기본값이 "asInvoker'…
Read More

[C#] 화면 캡쳐 하기

CSharp
WinForm 안의 Controler 를 캡쳐하기 string FileName = DateTime.Now.ToString("yyyyMMdd_HHmmss"); Bitmap bitmap = new Bitmap(width, height); this.panel1.DrawToBitmap(bitmap, new Rectangle(0, 0, width, height)); bitmap.Save(FileName + ".png", ImageFormat.Png); 스크린틀 캡쳐하는 기능 string FileName = DateTime.Now.ToString("yyyyMMdd_HHmmss"); Bitmap bitmap = new Bitmap(넓이, this.높이); Graphics g = Graphics.FromImage(bitmap); g.CopyFromScreen( PointToScreen(new Point(시작 X좌표, 시작 Y 좌표)), new Point(0, 0), new Pint(넓이, 높이)); bitmap.Save(FileName + ".png", ImageFormat.Png);
Read More
c# 에러 출력 예외 설정

c# 에러 출력 예외 설정

CSharp
VS -> 디버그 -> 창 -> 예외설정 -> ContextSwitchDeadlock 체크 해제 << 에러내용 >> CLR에서 60초 동안 COM 컨텍스트 0x1a18b8에서 COM 컨텍스트 0x1a1a28(으)로 전환하지 못했습니다.  대상 컨텍스트/아파트를 소유하는 스레드가 펌프 대기를 수행하지 않거나, Windows 메시지를 펌프하지 않고 매우 긴 실행 작업을 처리하고 있는 것 같습니다. 이러한 상황은 대개 성능에 부정적인 영향을 주며 응용 프로그램이 응답하지 않거나 시간이 흐름에 따라 메모리 사용이 증가하는 문제로 이어질 수도 있습니다. 이 문제를 방지하려면 모든 STA(Single Threaded Apartment) 스레드가 펌프 대기 기본 형식(예: CoWaitForMultipleHandles)을 사용하고 긴 실행 작업 동안 지속적으로 메시지를 펌프해야 합니다
Read More

Winform 환경설정 세팅 저장 장소

CSharp
Windows Application을 개발 할 때, 현재 상태의 설정값(사용자ID, 비밀번호, 포지션 등등... )을 저장하여 다음번 Load 시 다시 이용하려고 할 경우,   보통 Settings.settings에 키를 설정 하고 Properties.Settings.Default.세팅명 을 프로퍼티로 사용합니다.   Settings.settings에 아무런 설정이 없을 경우엔 app.config에 특별한 내용이 들어가지 않지만, Settings.settings에 세팅을 하나라도 설정하는 경우 app.config에   <configSections>     <sectionGroup name="userSettings" ...> ...   <userSettings>     <......Properties.Settings> ... #biki1983omi @netdoor!   등의 태그가 자동으로 포함됩니다.   로드시 Properties.Settings.Default.세팅명 을 이용하고, 저장시 Properties.Settings.Default.Save(); 메서드를 이용하면 됩니다.   Settings.settings에 설정할 시 '범위'는 '사용자'로 하여야 런타임시 저장할 수 있습니다. 런타임 시 ....exe.config에 값이 저장되는 것이 아니라,  C:\Users\사용자\AppData 하위의 해당 App 폴더에 값이 저장됩니다.   기본적으로 숨겨진 폴더이긴 해도, 비밀번호 등은 암호화 처리를 하는 것이 좋겠지요. ^^   가끔 네임스페이스 충돌로 인해 Full Namespace 즉, 네임스페이스.Properties.Settings.Default.세팅명 로 사용해야 하는 경우도 있으니 참고하세요.  …
Read More

소스보관

CSharp
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing.Imaging; using System.Net; using System.Collections; using System.Threading; using System.IO; using MySql.Data.MySqlClient; namespace FnbfoodNaverSmartstoreCapture { public partial class MainForm : Form { private string ConnectDB = "Server=211.233.11.93; Port=3306;Database=fnbfood;Uid=fnbfood;Pwd=@fnbfood!;Charset=utf8;convert zero datetime=True;"; private MySqlCommand command; private MySqlDataReader DBResult; public MainForm() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; this.DoubleBuffered = true; } private void MainForm_Load(object sender, EventArgs e) { DateTimeCheck(); } /// <summary> /// 웹을 실제 실행해야 되는지 체크하도록 함. /// </summary> private void DateTimeCheck() { string Week = System.DateTime.Now.ToString("ddd"); int TimeHM = Convert.ToInt32(System.DateTime.Now.ToString("Hmm")); switch (Week) { case "월": case "화": case "수": case "목": case "금": if (TimeHM > 750 && TimeHM < 1810) { this.Activate(); this.Show(); this.WindowState = FormWindowState.Normal; WebLoad(); } else {…
Read More

[C#] URL에서 XML 해석

CSharp
XmlDocument doc = new XmlDocument(); doc.Load("URL주소"); XmlNodeList forecastNodes = doc.SelectNodes("rss/channel/item"); foreach (XmlNode node in forecastNodes) { if (node["category"] != null) { if (node["category"].InnerText == "NOTICE") { string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz"; DateTimeOffset dto = DateTimeOffset.ParseExact(node["pubDate"].InnerText, parseFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None); DateTextbox.Text = dto.ToString("yyyy년 MM월 dd일 (ddd) tt h시 mm분"); break; } } }
Read More

[C#] HTML 에서 Text만 추출

CSharp
/// <summary> /// HTML 에서 Text만 추출한다. /// </summary> /// <param name="Html"></param> /// <returns></returns> public static string StripHtml(string Html) { string output = Html; output = System.Text.RegularExpressions.Regex.Replace(output, "<br>", Environment.NewLine); output = System.Text.RegularExpressions.Regex.Replace(output, "<br/>", Environment.NewLine); output = System.Text.RegularExpressions.Regex.Replace(output, "<br />", Environment.NewLine); //get rid of HTML tags output = System.Text.RegularExpressions.Regex.Replace(output, "<[^>]*>", string.Empty); //get rid of multiple blank lines output = System.Text.RegularExpressions.Regex.Replace(output, @"^\s*$\n", string.Empty, System.Text.RegularExpressions.RegexOptions.Multiline); output = System.Text.RegularExpressions.Regex.Replace(output, " ", " "); return output; }
Read More

C# serial communication

CSharp
using System; //using OpenNETCF.IO.Ports; using System.IO.Ports; namespace ConsoleApp1 { class Program { static void Main(string[] args) { SerialPort port = new SerialPort("COM43", 115200, Parity.None, 8, StopBits.One); port.Open(); System.Threading.Thread.Sleep(1000); // waiting for Arduino reset for (int i = 0; i < 1000; i++) { Console.WriteLine(port.BytesToRead); // it write on the console only zeros, so no data is received System.Threading.Thread.Sleep(100); } port.Close(); } } }
Read More
[C#] dll을 포함한 단일 exe배포 방법

[C#] dll을 포함한 단일 exe배포 방법

CSharp
일반적으로 프로그램을 배포시 exe파일과 Application이 호출하는 dll파일은 동일한 폴더(또는 dll 파일이 System폴더에 위치)에 있어야 한다. Microsoft 공식 배포처에서는 exe와 호출하는 라이브러리를 병합하는 프로그램을 배포중이지만, 컴파일러단에서 자체 해결할 수 있는 방법도 존재한다. 사용하고자 하는 dll을 프로젝트에 참조해당 dll을 프로젝트 리소스에 추가리소스에 추가된 dll의 속성 -> 빌드작업 속성 값을 포함 리소스로 지정프로그램 진입점(Program.cs)에 코드를 아래와 같이 변경리소스에 dll 파일 포함하기dll 파일 => 속성 => 빌드작업 ++ 포함리소스로 변경 using System.Reflection; using System.IO; /// <summary> /// 해당 응용 프로그램의 주 진입점입니다. /// </summary> [STAThread] static void Main() { // 리소스 dll 취득 AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveAssembly); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } // .NET 4.0 이상 static Assembly ResolveAssembly(object sender, ResolveEventArgs args) { Assembly thisAssembly = Assembly.GetExecutingAssembly(); var name = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll"; var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(name)); if (resources.Count() > 0)…
Read More