아래 코드를 이용하면 캡쳐를 방지할 수 있습니다.

using System;

using System.Drawing;

using System.Runtime.InteropServices;

using System.Windows.Forms;


namespace WindowsFormsApp

{

    public partial class MainForm : Form

    {

        private const uint WDA_NONE = 0;

        private const uint WDA_MONITOR = 1;


        [DllImport("user32.dll")]

        private static extern uint SetWindowDisplayAffinity(IntPtr windowHandle, uint affinity);


        public MainForm()

        {

            InitializeComponent();


            this.onButton.Click  += OnButton_Click;

            this.offButton.Click += OffButton_Click;

        }


        private void OnButton_Click(object sender, EventArgs e)

        {

            this.onButton.BackColor  = Color.White;

            this.offButton.BackColor = Color.Transparent;


            SetWindowDisplayAffinity(this.Handle, WDA_MONITOR);

        }


        private void OffButton_Click(object sender, EventArgs e)

        {

            this.onButton.BackColor  = Color.Transparent;

            this.offButton.BackColor = Color.White;


            SetWindowDisplayAffinity(this.Handle, WDA_NONE);

        }

    }

}



* 캡쳐도구를 이용해 캡쳐방지를 하지 않고 했을 때와  캡쳐방지를 켜고 했을 때 비교

(캡쳐방지를 켠 경우에는 녹화할 때도 검게변한다^^)


반디캠, 칼무리, 캡쳐도구, Print Screen 을 이용해 캡쳐 동작을 취할경우 검은 화면으로 보이게 된다.

메서드 호출시 메서드 안에서 어디에서 호출된 것인지 알고 싶을때가 있다

특히 로그 남길 때 유용하게 쓸수 있다.

아래 코드 처럼 메서드 인자로 [CallerMemberName], [CallerFilePath], [CallerLineNumber] 를 선언해 주면 알아서 내용이 들어가게된다.


using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows.Forms;

namespace CompilerServicesTest
{
    public partial class TestForm : Form
    {
        public TestForm()
        {
            InitializeComponent();

            CallMethod();
        }

        private void CallMethod()
        {
            WriteLog("CompilerServices Test!!");
        }

        private void WriteLog(string message,
           [CallerMemberName] string memberName = "",
           [CallerFilePath]   string sourceFilePath = "",
           [CallerLineNumber] int sourceLineNumber = 0)
        {
            Trace.WriteLine("message: " + message);
            Trace.WriteLine("member name: " + memberName);
            Trace.WriteLine("source file path: " + sourceFilePath);
            Trace.WriteLine("source line number: " + sourceLineNumber);
        }
    }
}



참고

https://docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/attributes/caller-information

            using System.Drawing.Text;

            using (InstalledFontCollection fontsCollection = new InstalledFontCollection())
            {
                FontFamily[] fontFamilies = fontsCollection.Families;
                List<string> fonts = new List<string>();
                foreach (FontFamily font in fontFamilies)
                {
                    fonts.Add(font.Name);
                }
             }

cmd 창에서 .net framework 경로로 이동

cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319


아래 명령어 실행

aspnet_regiis –i

기억을 위해 남긴다.

간단하게 웹 API 를 작성하고자 할때는 아래처럼 추가한후 Controller 를 추가해주면 된다.



string targetProcessPath = @"c:\windows\system32\notepad.exe";
string targetProcessName = "notepad";

Process[] runningProcesses = Process.GetProcesses();
foreach (Process process in runningProcesses)
{
    if (process.ProcessName == targetProcessName && 
        process.MainModule != null &&
        string.Compare(process.MainModule.FileName, targetProcessPath, StringComparison.InvariantCultureIgnoreCase)==0)
    {
        process.Kill();
    }
}


특정 위치의 exe 파일의 실행 프로세스를 Kill 하는 코드.

webRequest 호출시 (401) Unauthorized 에러가 발생한 경우 처리한다.

 

HttpWebRequest myReq = ...

myReq.UseDefaultCredentials = true;

myReq.PreAuthenticate      = true;

myReq.Credentials          = CredentialCache.DefaultCredentials;

 

 

참고

https://stackoverflow.com/questions/10205854/error-the-remote-server-returned-an-error-401-unauthorized

어느날 C 드라이브가 용량이 좀 차서

파일을 정리하는데 엄청난양의 Nuget Package 파일들이 디스크 용량을

잡아 먹고 있는걸 확인했다.

이를 수동으로 지우기 보다는 Visual Studio 에서 지우는 방법이 있다.

Visual Studio 에서 도구>옵션 의 옵션창에서

Nuget 패키지 관리자를 선택하면 '모든 NuGet 캐시 지우기' 버튼이 있는데

이를 클릭하면 삭제 할수 있다.

 

1.

https://stackoverflow.com/questions/989281/how-can-i-programmatically-limit-my-programs-cpu-usage-to-below-70

아래 내용은 Process.Start() 이후

process.PriorityClass = ProcessPriorityClass.BelowNormal;

처리를 해줘야 효과를 볼수 있다.

 

    public static class ProcessHelper

    {

        [Flags]

        public enum ThreadAccess : int

        {

            TERMINATE = (0x0001),

            SUSPEND_RESUME = (0x0002),

            GET_CONTEXT = (0x0008),

            SET_CONTEXT = (0x0010),

            SET_INFORMATION = (0x0020),

            QUERY_INFORMATION = (0x0040),

            SET_THREAD_TOKEN = (0x0080),

            IMPERSONATE = (0x0100),

            DIRECT_IMPERSONATION = (0x0200)

        }

 

        [DllImport("kernel32.dll")]

        static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);

 

        [DllImport("kernel32.dll")]

        static extern uint SuspendThread(IntPtr hThread);

 

        [DllImport("kernel32.dll")]

        static extern int ResumeThread(IntPtr hThread);

 

        [DllImport("kernel32.dll")]

        static extern int CloseHandle(IntPtr hThread);

 

        public static void ThrottleProcess(int processId, double limit)

        {

            var process = Process.GetProcessById(processId);

            var processName = process.ProcessName;

            var p = new PerformanceCounter("Process", "% Processor Time", processName);

            while (true)

            {

                var interval = 100;

                Thread.Sleep(interval);

 

                var currentUsage = p.NextValue() / Environment.ProcessorCount;

                if (currentUsage < limit) continue;

                var suspensionTime = (currentUsage-limit) / currentUsage * interval;

                SuspendProcess(processId);

                Thread.Sleep((int)suspensionTime);

                ResumeProcess(processId);

            }

        }

 

        private static void SuspendProcess(int pid)

        {

            var process = Process.GetProcessById(pid);

 

            if (process.ProcessName == string.Empty)

                return;

 

            foreach (ProcessThread pT in process.Threads)

            {

                IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);

 

                if (pOpenThread == IntPtr.Zero)

                {

                    continue;

                }

 

                SuspendThread(pOpenThread);

 

                CloseHandle(pOpenThread);

            }

        }

 

        private static void ResumeProcess(int pid)

        {

            var process = Process.GetProcessById(pid);

 

            if (process.ProcessName == string.Empty)

                return;

 

            foreach (ProcessThread pT in process.Threads)

            {

                IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);

 

                if (pOpenThread == IntPtr.Zero)

                {

                    continue;

                }

 

                var suspendCount = 0;

 

                do

                {

                    suspendCount = ResumeThread(pOpenThread);

                } while (suspendCount > 0);

 

                CloseHandle(pOpenThread);

            }

        }

    }

 

2.

https://stackoverflow.com/questions/989281/how-can-i-programmatically-limit-my-programs-cpu-usage-to-below-70

 

아래 내용은 process.PriorityClass = ProcessPriorityClass.BelowNormal 처리를 하지 않아도 효과를 볼수 있다.

이 내용이 확실하게 제어를 해주는것 같다

 

    public class ProcessManager

    {

        [DllImport("kernel32.dll", EntryPoint = "CreateJobObjectW", CharSet = CharSet.Unicode)]

        public static extern IntPtr CreateJobObject(SecurityAttributes JobAttributes, string lpName);

 

        [DllImport("kernel32.dll")]

        [return: MarshalAs(UnmanagedType.Bool)]

        static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);

 

        [DllImport("kernel32.dll")]

        static extern bool SetInformationJobObject(IntPtr hJob, JOBOBJECTINFOCLASS JobObjectInfoClass, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);

 

        public class SecurityAttributes

        {

            public int nLength;

            public IntPtr pSecurityDescriptor;

            public bool bInheritHandle;

 

            public SecurityAttributes()

            {

                this.bInheritHandle = true;

                this.nLength = 0;

                this.pSecurityDescriptor = IntPtr.Zero;

            }

        }

 

        public enum JOBOBJECTINFOCLASS

        {

            JobObjectAssociateCompletionPortInformation = 7,

            JobObjectBasicLimitInformation = 2,

            JobObjectBasicUIRestrictions = 4,

            JobObjectEndOfJobTimeInformation = 6,

            JobObjectExtendedLimitInformation = 9,

            JobObjectSecurityLimitInformation = 5,

            JobObjectCpuRateControlInformation = 15

        }

 

        [StructLayout(LayoutKind.Explicit)]

        //[CLSCompliant(false)]

        struct JOBOBJECT_CPU_RATE_CONTROL_INFORMATION

        {

            [FieldOffset(0)]

            public UInt32 ControlFlags;

            [FieldOffset(4)]

            public UInt32 CpuRate;

            [FieldOffset(4)]

            public UInt32 Weight;

        }

 

        public enum CpuFlags

        {

            JOB_OBJECT_CPU_RATE_CONTROL_ENABLE = 0x00000001,

            JOB_OBJECT_CPU_RATE_CONTROL_WEIGHT_BASED = 0x00000002,

            JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP = 0x00000004

        }

 

        public static void ThrottleProcess(Process process)

        {

            //Limit the CPU usage to 45%

            var jobHandle = CreateJobObject(null, null);

            AssignProcessToJobObject(jobHandle, process.Handle);

            var cpuLimits = new JOBOBJECT_CPU_RATE_CONTROL_INFORMATION();

            cpuLimits.ControlFlags = (UInt32)(CpuFlags.JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | CpuFlags.JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP);

            cpuLimits.CpuRate = 45 * 100; // Limit CPu usage to 45%

            var pointerToJobCpuLimits = Marshal.AllocHGlobal(Marshal.SizeOf(cpuLimits));

            Marshal.StructureToPtr(cpuLimits, pointerToJobCpuLimits, false);

            if (!SetInformationJobObject(jobHandle, JOBOBJECTINFOCLASS.JobObjectCpuRateControlInformation, pointerToJobCpuLimits, (uint)Marshal.SizeOf(cpuLimits)))

            {

                Console.WriteLine("Error !");

            }

        }

    }

 

 

사용예시

 

Process process = new Process();

process.EnableRaisingEvents   = false;

process.StartInfo.FileName    = "Test.exe";

//process.StartInfo.Verb        = "Open";

process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

//process.StartInfo.Arguments   = argument;

 

process.Start();

 

// 1번 방법

process.PriorityClass = ProcessPriorityClass.BelowNormal;

ProcessHelper.ThrottleProcess(process.Id, 0.5);

 

// 2번 방법

ProcessManager.ThrottleProcess(process);

 

        #region ImageToBytes

        /// <summary>

        /// 이미지를 바이트 배열로 변환합니다.

        /// </summary>

        /// <param name="image">변환할 이미지입니다.</param>

        /// <returns>바이트배열입니다.</returns>

        byte[] ImageToBytes(Image image)

        {

            // 이미지 포멧을 가져옵니다.

            ImageFormat imageFormat = image.RawFormat;

            using (MemoryStream memoryStream = new MemoryStream())

            {

                // 이미지 포멧에 따라 스트림에 이미지를 저장합니다.

                if (imageFormat.Equals(ImageFormat.Jpeg))

                {

                    image.Save(memoryStream, ImageFormat.Jpeg);

                }

                else if (imageFormat.Equals(ImageFormat.Png))

                {

                    image.Save(memoryStream, ImageFormat.Png);

                }

                else if (imageFormat.Equals(ImageFormat.Bmp))

                {

                    image.Save(memoryStream, ImageFormat.Bmp);

                }

                else if (imageFormat.Equals(ImageFormat.Gif))

                {

                    image.Save(memoryStream, ImageFormat.Gif);

                }

                else if (imageFormat.Equals(ImageFormat.Icon))

                {

                    image.Save(memoryStream, ImageFormat.Icon);

                }

 

                // 배열을 선언합니다.

                byte[] buffer = new byte[memoryStream.Length];

 

                // 배열을 체웁니다.

                memoryStream.Seek(0, SeekOrigin.Begin);

                memoryStream.Read(buffer, 0, buffer.Length);

 

                return buffer;

            }

        }

        #endregion

+ Recent posts