Get it on Google Play


Wm뮤 :: '윈도우폼' 카테고리의 글 목록 (2 Page)

블로그 이미지
가끔 그림그리거나 3D모델링하거나
취미로 로봇만드는
전자과 게임프로그래머 (퇴사함)
2022.3.22f1 주로 사용
모카쨩
@Ahzkwid

Recent Comment

Archive


'윈도우폼'에 해당되는 글 12건

  1. 2021.01.17 윈폼 키보드마우스
  2. 2020.11.23 c# 멀티스레드 기본소스
  3. 2020.10.31 자주 쓰는 윈폼 코드 모음
  4. 2018.01.28 c# 윈도우 폼
2021. 1. 17. 04:56 윈도우폼
    public static class mMouse
    {
        [DllImport("User32.dll")]
        public static extern int SetCursorPos(int x, int y);
        [DllImport("User32.dll")]
        public static extern int GetCursorPos(ref Point pos);

        [DllImport("user32.dll")] // 마우스 입력 
        static extern void mouse_event(uint dwFlags, uint dx, uint dy, int dwData, int dwExtraInfo);

        [System.Runtime.InteropServices.DllImport("User32.dll")] //마우스 상태
        public static extern int GetKeyboardState(ref byte[] pbKeyState);

        [DllImport("User32.dll")]
        public static extern short GetKeyState(int nVirtualKey);

        [DllImport("user32.dll")]
        static extern void keybd_event(byte vk, byte scan, int flags, int extrainfo);

        /*
        
            const byte AltKey = 18;
            const int KEYUP = 0x0002;    
            int Info=0;
            keybd_event(AltKey, 0, 0, ref Info);   // ALT key 다운
            keybd_event(AltKey, 0, KEYUP, ref Info);  // ALT key 업
        */
        //[System.Runtime.InteropServices.DllImport("user32.dll")] //마우스 상태
        //[return: MarshalAs(UnmanagedType.Bool)]
        //public static extern bool GetKeyboardState(byte[] pbKeyState);

        #region mouse_flag
        private const uint
            Absolute = 0x8000,
            LeftDown = 0x0002,
            LeftUp = 0x0004,
            MiddleDown = 0x0020,
            MiddleUp = 0x0040,
            Move = 0x0001,
            RightDown = 0x0008,
            RightUp = 0x0010,
            Wheel = 0x0800,
            XDown = 0x0080,
            XUp = 0x0100,
            HWheel = 0x1000;
        #endregion

        #region mouse_state
        private const byte
            LeftButton = 1,
            MiddleButton = 4,
            RightButton = 2;
        #endregion

        private static byte[] key_state = new byte[256];
        //public static mVec2 pos;

        public static int x
        {
            get
            {
                Point _pos = new Point();
                GetCursorPos(ref _pos);
                return _pos.X;
            }
            set
            {
                SetCursorPos(value, y);
            }
        }
        public static int y
        {
            get
            {
                Point _pos = new Point();
                GetCursorPos(ref _pos);
                return _pos.Y;
            }
            set
            {
                SetCursorPos(x, value);
            }
        }
        public static Point pos
        {
            get
            {
                Point _pos = new Point();
                GetCursorPos(ref _pos);
                return new Point(_pos.X, _pos.Y);
            }
            set
            {
                SetCursorPos((int)value.X, (int)value.Y);
            }
        }

        public static bool left
        {
            get
            {
                return (GetKeyState(LeftButton) & 0x80) != 0;
            }
            set
            {
                //uint _flag_t;
                if (value)
                {
                    //keybd_event(0x01, 0, 0,0);   // ALT key 다운
                    mouse_event(LeftDown, 0, 0, 0, 0);
                }
                else
                {
                    //keybd_event(0x01, 0, 0x0002, 0);   // ALT key 다운
                    mouse_event(LeftUp, 0, 0, 0, 0);
                }
            }
        }
    }

 

 

 


    public static class mKey
    {
        [DllImport("User32.dll")]
        public static extern short GetKeyState(int nVirtualKey);

        [System.Runtime.InteropServices.DllImport("user32.dll")] //키보드 상태
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern int GetKeyboardState(byte[] pbKeyState);

        [DllImport("user32.dll")]
        static extern void keybd_event(byte vk, byte scan, int flags, int extrainfo);

        private static bool hangleToggle = false;

        #region keyState
        private const int
            key_down = 0x0000,
            key_up = 0x0002;
        #endregion

        #region kr_key_index_array
        private static string[]
            krSyllableFirst =
            {
                "ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ",
                "ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"
            },
            krSyllableSecond =
            {
                "ㅏ","ㅐ","ㅑ","ㅒ","ㅓ","ㅔ","ㅕ","ㅖ","ㅗ","ㅗㅏ",
                "ㅗㅐ","ㅗㅣ","ㅛ","ㅜ","ㅜㅓ","ㅜㅔ","ㅜㅣ","ㅠ","ㅡ","ㅡㅣ",
                "ㅣ"
            },
            krSyllableThird =
            {
                "","ㄱ","ㄲ","ㄱㅅ","ㄴ","ㄴㅈ","ㄴㅎ","ㄷ","ㄹ","ㄹㄱ",
                "ㄹㅁ","ㄹㅂ","ㄹㅅ","ㄹㅌ","ㄹㅍ","ㄹㅎ","ㅁ","ㅂ","ㅂㅅ","ㅅ",
                "ㅆ","ㅇ","ㅈ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"
            };
        #endregion


        #region VirtualKey
        public static byte


            vk_backspace = 0x08,
            vk_back = vk_backspace,  //BACKSPACE key

            vk_return = 0x0D,  //ENTER key
            vk_enter = vk_return,  //ENTER key

            vk_shift = 0x10,  //SHIFT key
            vk_control = 0x11,  //CTRL key
            vk_ctrl = vk_control,  //CTRL key


            vk_capital = 0x14,  //CAPS LOCK key
            vk_cap = vk_capital,  //CAPS LOCK key

            vk_hangul = 0x15, //hangul

            vk_escape = 0x1B,  //ESC key
            vk_esc = vk_escape,  //ESC key

            vk_space = 0x20,  //SPACEBAR


            vk_left = 0x25,  //LEFT ARROW key
            vk_le = vk_left,  //LEFT ARROW key
            vk_up = 0x26,  //UP ARROW key
            vk_right = 0x27,  //RIGHT ARROW key
            vk_ri = vk_right,  //RIGHT ARROW key
            vk_down = 0x28,  //DOWN ARROW key
            vk_do = vk_down,  //DOWN ARROW key




            vk_0 = 0x30,  //0 key
            vk_1 = 0x31,  //1 key
            vk_2 = 0x32,  //2 key
            vk_3 = 0x33,  //3 key
            vk_4 = 0x34,  //4 key
            vk_5 = 0x35,  //5 key
            vk_6 = 0x36,  //6 key
            vk_7 = 0x37,  //7 key
            vk_8 = 0x38,  //8 key
            vk_9 = 0x39,  //9 key
            vk_a = 0x41,  //A key
            vk_b = 0x42,  //B key
            vk_c = 0x43,  //C key
            vk_d = 0x44,  //D key
            vk_e = 0x45,  //E key
            vk_f = 0x46,  //F key
            vk_g = 0x47,  //G key
            vk_h = 0x48,  //H key
            vk_i = 0x49,  //I key
            vk_j = 0x4A,  //J key
            vk_k = 0x4B,  //K key
            vk_l = 0x4C,  //L key
            vk_m = 0x4D,  //M key
            vk_n = 0x4E,  //N key
            vk_o = 0x4F,  //O key
            vk_p = 0x50,  //P key
            vk_q = 0x51,  //Q key
            vk_r = 0x52,  //R key
            vk_s = 0x53,  //S key
            vk_t = 0x54,  //T key
            vk_u = 0x55,  //U key
            vk_v = 0x56,  //V key
            vk_w = 0x57,  //W key
            vk_x = 0x58,  //X key
            vk_y = 0x59,  //Y key
            vk_z = 0x5A,  //Z key




            vk_multiply = 0x6A,  // *
            vk_add = 0x6B,  // +
            vk_separator = 0x6C,  //Separator key
            vk_subtract = 0x6D,  // - 
            vk_decimal = 0x6E,  //.
            vk_divide = 0x6F,  // / key


            vk_oem_1 = 0xBA,  // ; :

            vk_oem_plus = 0xBB,  // = +
            vk_oem_comma = 0xBC,  // , <
            vk_oem_minus = 0xBD,  // - _
            vk_oem_period = 0xBE,  // . >

            vk_oem_2 = 0xBF,  // / ?
            vk_oem_3 = 0xC0,  // ` ~



            vk_oem_4 = 0xDB,  // [ {
            vk_oem_5 = 0xDC,  // \ |
            vk_oem_6 = 0xDD,  // ] }


            vk_oem_7 = 0xDE,  // ' "
            vk_oem_8 = 0xDf  //




        ;
        #endregion

        #region VirtualKey2
        public static int VK_LBUTTON = 0x01,  //Left mouse button
            VK_RBUTTON = 0x02,  //Right mouse button
            VK_CANCEL = 0x03,  //Control-break processing
            VK_MBUTTON = 0x04,  //Middle mouse button (three-button mouse)
            VK_BACK = 0x08,  //BACKSPACE key
            VK_TAB = 0x09,  //TAB key
            VK_CLEAR = 0x0C,  //CLEAR key
            VK_RETURN = 0x0D,  //ENTER key
            VK_SHIFT = 0x10,  //SHIFT key
            VK_CONTROL = 0x11,  //CTRL key
            VK_MENU = 0x12,  //ALT key
            VK_PAUSE = 0x13,  //PAUSE key
            VK_CAPITAL = 0x14,  //CAPS LOCK key
            VK_HANGUL = 0x15,
            VK_ESCAPE = 0x1B,  //ESC key
            VK_SPACE = 0x20,  //SPACEBAR
            VK_PRIOR = 0x21,  //PAGE UP key
            VK_NEXT = 0x22,  //PAGE DOWN key
            VK_END = 0x23,  //END key
            VK_HOME = 0x24,  //HOME key
            VK_LEFT = 0x25,  //LEFT ARROW key
            VK_UP = 0x26,  //UP ARROW key
            VK_RIGHT = 0x27,  //RIGHT ARROW key
            VK_DOWN = 0x28,  //DOWN ARROW key
            VK_SELECT = 0x29,  //SELECT key
            VK_PRINT = 0x2A,  //PRINT key
            VK_EXECUTE = 0x2B,  //EXECUTE key
            VK_SNAPSHOT = 0x2C,  //PRINT SCREEN key
            VK_INSERT = 0x2D,  //INS key
            VK_DELETE = 0x2E,  //DEL key
            VK_HELP = 0x2F,  //HELP key
            VK_0 = 0x30,  //0 key
            VK_1 = 0x31,  //1 key
            VK_2 = 0x32,  //2 key
            VK_3 = 0x33,  //3 key
            VK_4 = 0x34,  //4 key
            VK_5 = 0x35,  //5 key
            VK_6 = 0x36,  //6 key
            VK_7 = 0x37,  //7 key
            VK_8 = 0x38,  //8 key
            VK_9 = 0x39,  //9 key
            VK_A = 0x41,  //A key
            VK_B = 0x42,  //B key
            VK_C = 0x43,  //C key
            VK_D = 0x44,  //D key
            VK_E = 0x45,  //E key
            VK_F = 0x46,  //F key
            VK_G = 0x47,  //G key
            VK_H = 0x48,  //H key
            VK_I = 0x49,  //I key
            VK_J = 0x4A,  //J key
            VK_K = 0x4B,  //K key
            VK_L = 0x4C,  //L key
            VK_M = 0x4D,  //M key
            VK_N = 0x4E,  //N key
            VK_O = 0x4F,  //O key
            VK_P = 0x50,  //P key
            VK_Q = 0x51,  //Q key
            VK_R = 0x52,  //R key
            VK_S = 0x53,  //S key
            VK_T = 0x54,  //T key
            VK_U = 0x55,  //U key
            VK_V = 0x56,  //V key
            VK_W = 0x57,  //W key
            VK_X = 0x58,  //X key
            VK_Y = 0x59,  //Y key
            VK_Z = 0x5A,  //Z key
            VK_NUMPAD0 = 0x60,  //Numeric keypad 0 key
            VK_NUMPAD1 = 0x61,  //Numeric keypad 1 key
            VK_NUMPAD2 = 0x62,  //Numeric keypad 2 key
            VK_NUMPAD3 = 0x63,  //Numeric keypad 3 key
            VK_NUMPAD4 = 0x64,  //Numeric keypad 4 key
            VK_NUMPAD5 = 0x65,  //Numeric keypad 5 key
            VK_NUMPAD6 = 0x66,  //Numeric keypad 6 key
            VK_NUMPAD7 = 0x67,  //Numeric keypad 7 key
            VK_NUMPAD8 = 0x68,  //Numeric keypad 8 key
            VK_NUMPAD9 = 0x69,  //Numeric keypad 9 key
            VK_SEPARATOR = 0x6C,  //Separator key
            VK_SUBTRACT = 0x6D,  //Subtract key
            VK_DECIMAL = 0x6E,  //Decimal key
            VK_DIVIDE = 0x6F,  //Divide key
            VK_F1 = 0x70,  //F1 key
            VK_F2 = 0x71,  //F2 key
            VK_F3 = 0x72,  //F3 key
            VK_F4 = 0x73,  //F4 key
            VK_F5 = 0x74,  //F5 key
            VK_F6 = 0x75,  //F6 key
            VK_F7 = 0x76,  //F7 key
            VK_F8 = 0x77,  //F8 key
            VK_F9 = 0x78,  //F9 key
            VK_F10 = 0x79,  //F10 key
            VK_F11 = 0x7A,  //F11 key
            VK_F12 = 0x7B,  //F12 key
            VK_SCROLL = 0x91,  //SCROLL LOCK key
            VK_LSHIFT = 0xA0,  //Left SHIFT key
            VK_RSHIFT = 0xA1,  //Right SHIFT key
            VK_LCONTROL = 0xA2,  //Left CONTROL key
            VK_RCONTROL = 0xA3,  //Right CONTROL key
            VK_LMENU = 0xA4,   //Left MENU key
            VK_RMENU = 0xA5,  //Right MENU key
            VK_PLAY = 0xFA,  //Play key
            VK_ZOOM = 0xFB //Zoom key
            ;
        #endregion

        private static byte[] keyState = new byte[256];

        public static bool enter
        {
            get
            {
                return KeyboardCheck(vk_enter);
            }
            set
            {
                if (value)
                {
                    keybd_event(vk_enter, 0, key_down, 0);
                }
                else
                {
                    keybd_event(vk_enter, 0, key_up, 0);
                }
            }
        }
        public static bool esc
        {
            get
            {
                return KeyboardCheck(vk_esc);
            }
            set
            {
                if (value)
                {
                    keybd_event(vk_esc, 0, key_down, 0);
                }
                else
                {
                    keybd_event(vk_esc, 0, key_up, 0);
                }
            }
        }
        public static bool shift
        {
            get
            {
                return KeyboardCheck(vk_shift);
            }
            set
            {
                if (value)
                {
                    keybd_event(vk_shift, 0, key_down, 0);
                }
                else
                {
                    keybd_event(vk_shift, 0, key_up, 0);
                }
            }
        }
        public static bool space
        {
            get
            {
                return KeyboardCheck(vk_space);
            }
            set
            {
                if (value)
                {
                    keybd_event(vk_space, 0, key_down, 0);
                }
                else
                {
                    keybd_event(vk_space, 0, key_up, 0);
                }
            }
        }
        public static bool back
        {
            get
            {
                return KeyboardCheck(vk_back);
            }
            set
            {
                if (value)
                {
                    keybd_event(vk_back, 0, key_down, 0);
                }
                else
                {
                    keybd_event(vk_back, 0, key_up, 0);
                }
            }
        }
        public static bool ctrl
        {
            get
            {
                return KeyboardCheck(vk_ctrl);
            }
            set
            {
                if (value)
                {
                    keybd_event(vk_ctrl, 0, key_down, 0);
                }
                else
                {
                    keybd_event(vk_ctrl, 0, key_up, 0);
                }
            }
        }
        public static bool hangul
        {
            get
            {
                return hangleToggle;
            }
            set
            {
                if (value != hangul)
                {
                    keybd_event(vk_hangul, 0, key_down, 0);
                    keybd_event(vk_hangul, 0, key_up, 0);
                    hangleToggle = value;
                }
            }
        }
        public static bool cap
        {
            get
            {
                return KeyboardCheckToggle(vk_cap);
            }
            set
            {
                if (value != cap)
                {
                    keybd_event(vk_cap, 0, key_down, 0);
                    keybd_event(vk_cap, 0, key_up, 0);
                }
            }
        }
        public static bool KeyCheck(int key)
        {
            return KeyboardCheck(key);
        }
        public static bool KeyCheckToggle(int key)
        {
            return KeyboardCheckToggle(key);
        }
        public static bool KeyboardCheckToggle(int key)
        {
            return (GetKeyState(key) & 0x0001) != 0;
            // GetKeyboardState(keyState);
        }
        public static bool KeyboardCheck(int key)
        {
            return (GetKeyState(key) & 0x8000) > 0;
            // GetKeyboardState(keyState);
        }
        public static void KeyPress(string text)
        {

            byte[] keycodes = ConvertKeycode(text);
            bool[] checkShiftCharacters = CheckShiftCharacter(text);
            bool[] bo_hangul = ConvertToSimpleAndIfKr(text);



            for (int i = 0; i < keycodes.Length; i++)
            {

                shift = checkShiftCharacters[i];
                if (hangul != bo_hangul[i])
                {
                    hangul = bo_hangul[i];
                    Thread.Sleep(200);
                }
                keybd_event(keycodes[i], 0, key_down, 0);
                keybd_event(keycodes[i], 0, key_up, 0);
            }
            shift = false;
            if (hangul != false)
            {
                space = true;
                space = false;

                back = true;
                back = false;

                hangul = false;
                Thread.Sleep(200);
            }
        }


        public static bool KrExists(string text)
        {
            return Array.Find(CheckKrCharacter(text), x => x == true);
        }
        public static bool[] ConvertToSimpleAndIfKr(string text)
        {
            return CheckKrCharacter(ConvertKrKey(text));
        }
        public static bool[] CheckKrCharacter(string text)
        {
            return System.Array.ConvertAll(text.ToCharArray(), x => CheckKrCharacter(x));
        }
        public static bool CheckKrCharacter(char character)
        {
            return ((character >= 0x1100) && (character <= 0x11FF))
                || ((character >= 0x3131) && (character <= 0x319E))
                || ((character >= 0xAC00) && (character <= 0xD7A3));
        }

        public static bool CheckCompletionKr(char character)
        {
            return (character >= 0xAC00) && (character <= 0xD7A3);
        }

        public static byte[] ConvertKeycode(string text)
        {
            return System.Array.ConvertAll(ConvertKrKey(text).ToCharArray(), x => ConvertKeycode(x)); 
        }
        public static byte ConvertKeycode(char character)
        {
            switch (character)
            {

                case '\n':
                    return vk_enter;

                case ';':
                case ':':
                    return vk_oem_1;
                case '/':
                case '?':
                    return vk_oem_2;
                case '`':
                case '~':
                    return vk_oem_3;
                case '[':
                case '{':
                    return vk_oem_4;
                case '\\':
                case '|':
                    return vk_oem_5;
                case ']':
                case '}':
                    return vk_oem_6;
                case '\'':
                case '"':
                    return vk_oem_7;
                case '=':
                case '+':
                    return vk_oem_plus;
                case '-':
                case '_':
                    return vk_oem_minus;
                case ',':
                case '<':
                    return vk_oem_comma;
                case '.':
                case '>':
                    return vk_oem_period;

                case ' ':
                    return vk_space;
                case '0':
                case ')':
                    return vk_0;
                case '1':
                case '!':
                    return vk_1;
                case '2':
                case '@':
                    return vk_2;
                case '3':
                case '#':
                    return vk_3;
                case '4':
                case '$':
                    return vk_4;
                case '5':
                case '%':
                    return vk_5;
                case '6':
                case '^':
                    return vk_6;
                case '7':
                case '&':
                    return vk_7;
                case '8':
                case '*':
                    return vk_8;
                case '9':
                case '(':
                    return vk_9;
                case 'a':
                case 'A':
                case 'ㅁ':
                    return vk_a;
                case 'b':
                case 'B':
                case 'ㅠ':
                    return vk_b;
                case 'c':
                case 'C':
                case 'ㅊ':
                    return vk_c;
                case 'd':
                case 'D':
                case 'ㅇ':
                    return vk_d;
                case 'e':
                case 'E':
                case 'ㄷ':
                case 'ㄸ':
                    return vk_e;
                case 'f':
                case 'F':
                case 'ㄹ':
                    return vk_f;
                case 'g':
                case 'G':
                case 'ㅎ':
                    return vk_g;
                case 'h':
                case 'H':
                case 'ㅗ':
                    return vk_h;
                case 'i':
                case 'I':
                case 'ㅑ':
                    return vk_i;
                case 'j':
                case 'J':
                case 'ㅓ':
                    return vk_j;
                case 'k':
                case 'K':
                case 'ㅏ':
                    return vk_k;
                case 'l':
                case 'L':
                case 'ㅣ':
                    return vk_l;
                case 'm':
                case 'M':
                case 'ㅡ':
                    return vk_m;
                case 'n':
                case 'N':
                case 'ㅜ':
                    return vk_n;
                case 'o':
                case 'O':
                case 'ㅐ':
                case 'ㅒ':
                    return vk_o;
                case 'p':
                case 'P':
                case 'ㅔ':
                case 'ㅖ':
                    return vk_p;
                case 'q':
                case 'Q':
                case 'ㅂ':
                case 'ㅃ':
                    return vk_q;
                case 'r':
                case 'R':
                case 'ㄱ':
                case 'ㄲ':
                    return vk_r;
                case 's':
                case 'S':
                case 'ㄴ':
                    return vk_s;
                case 't':
                case 'T':
                case 'ㅅ':
                case 'ㅆ':
                    return vk_t;
                case 'u':
                case 'U':
                case 'ㅕ':
                    return vk_u;
                case 'v':
                case 'V':
                case 'ㅍ':
                    return vk_v;
                case 'w':
                case 'W':
                case 'ㅈ':
                case 'ㅉ':
                    return vk_w;
                case 'x':
                case 'X':
                case 'ㅌ':
                    return vk_x;
                case 'y':
                case 'Y':
                case 'ㅛ':
                    return vk_y;
                case 'z':
                case 'Z':
                case 'ㅋ':
                    return vk_z;
            }
            return 0;
        }

        public static bool[] CheckShiftCharacter(string text)
        {
            return System.Array.ConvertAll(ConvertKrKey(text).ToCharArray(), x => CheckShiftCharacter(x));
        }
        public static bool CheckShiftCharacter(char character)
        {
            switch (character)
            {



                case '<':
                case '>':
                case '?':
                case '"':
                case ':':
                case '{':
                case '}':
                case '_':
                case '+':
                case '|':
                case '~':

                case ')':
                case '!':
                case '@':
                case '#':
                case '$':
                case '%':
                case '&':
                case '*':
                case '^':
                case '(':

                case 'A':
                case 'B':
                case 'C':
                case 'D':
                case 'E':
                case 'ㄸ':
                case 'F':
                case 'G':
                case 'H':
                case 'I':
                case 'J':
                case 'K':
                case 'L':
                case 'M':
                case 'N':
                case 'O':
                case 'ㅒ':
                case 'P':
                case 'ㅖ':
                case 'Q':
                case 'ㅃ':
                case 'R':
                case 'ㄲ':
                case 'S':
                case 'T':
                case 'ㅆ':
                case 'U':
                case 'V':
                case 'W':
                case 'ㅉ':
                case 'X':
                case 'Y':
                case 'Z':
                    return true;
            }
            return false;
        }

        public static string ConvertKrKey(string text)
        {
            return string.Concat(System.Array.ConvertAll(text.ToCharArray(), x => ConvertKrKey(x)));
        }
        public static string ConvertKrKey(char character)
        {
            string text = "";
            if (!CheckCompletionKr(character))
            {
                text += character;
                return text;
            }
            int char_number = character - 0xAC00;
            text += krSyllableFirst[char_number / (28 * 21)];
            text += krSyllableSecond[(char_number % (28 * 21)) / 28];
            text += krSyllableThird[char_number % 28];
            return text;
        }

    }

'윈도우폼' 카테고리의 다른 글

DLL 생성 예제  (0) 2021.02.11
c# 멀티스레드 기본소스  (0) 2020.11.23
자주 쓰는 윈폼 코드 모음  (0) 2020.10.31
posted by 모카쨩
2020. 11. 23. 16:26 윈도우폼

c# 멀티스레드풀 기본소스

(2015년에 짠 코드라 그렇지 이미지처리를 CPU로 하는 병신짓은 하지말자)

using System.Collections;



public bool multi_threadpool_MC(float[,] img1f)
{
    int img1wid = img1f.GetLength(0); // 기준 이미지 너비
    int img1hei = img1f.GetLength(1); //기준 이미지 높이

    int coreNum = 64; //스레드풀 갯수 설정

    EventWaitHandle[] threadSig = new EventWaitHandle[coreNum]; //스레드풀 계산 완료 시그널
    Hashtable[] ht_t = new Hashtable[coreNum];
    for (int i = 0; i < coreNum; i++)
    {
        threadSig[i] = new EventWaitHandle(false, EventResetMode.ManualReset);//서브스레드 대기 시그널 생성
        ht_t[i] = new Hashtable(); //인자를 전달할 해쉬테이블 생성
        ht_t[i]["num"] = i;
        ht_t[i]["coreNum"] = coreNum; //인자 박싱
        ht_t[i]["threadSig"] = threadSig[i];

        ht_t[i]["img1f"] = img1f; //계산처리할 데이터
        ht_t[i]["return"] = false; //반환값

        ThreadPool.QueueUserWorkItem(image_search_MC_thread, ht_t[i]);
    }
    WaitHandle.WaitAll(threadSig); //스레드 처리 완료 대기(최대 64개)
/*
  혹은
  for (i=0; i<coreNum; i++) 
  {
   threadSig[i].WaitOne();//스레드 처리 완료 대기
  }
*/
    bool _return_t = false;
    for (int i = 0; i < core_num; i++)
    {
        _return_t = _return_t || (bool)ht_t[i]["return"];
    }
    return _return_t;
}
private static void image_search_MC_thread(object hashtable_var)
{
    Hashtable ht = (Hashtable)hashtable_var; //오브젝트 언박싱


    int num = (int)ht["num"];
    int core_num = (int)ht["coreNum"];

    float[,] img1f = (float[,])ht["img1f"]; //해시테이블 언박싱
    int img1wid = img1f.GetLength(0); //1번째 차원 길이
    int img1hei = img1f.GetLength(1); //2번째 차원 길이
    for (int i = num; i < img1wid; i += core_num) //분산처리
    {
        for (int j = 0; j < img1hei; j++)
        {
            if (i==j) // 반환된 값이 True일 경우
            {
                ht["return"] = true;
            }

        }
    }

    //ht["return"] = false;
    ((EventWaitHandle)ht["_thread_sig"]).Set();
}

 

 

심플버전

    using UnityEngine;
    using System.Collections;
    using System.Threading; //스레드 시스템을 호출
    using System; //스레드에서 계산을 위해 닷넷 시스템 호출

    public class MultiThread : MonoBehaviour
    {
        private Thread thread;
        private EventWaitHandle threadSig;
        void Awake()
        {
            threadSig = new EventWaitHandle(false, EventResetMode.ManualReset);//서브스레드 대기 시그널 생성
            thread = new Thread(SubThread); //스레드를 생성
            thread.IsBackground = true; //백그라운드에서 동작(메인스레드의 하위로 들어감)
            thread.Start(); //스레드 시작

//기다리는동안 처리될코드

            threadSig.WaitOne();//서브스레드 처리 완료 대기중
            threadSig.Reset();//수신완료 리셋
        }
        private void SubThread()
        {
            //여기에 처리시킬 코드를 넣습니다 


            threadSig.Set(); //서브스레드 종료알림
        }
    }

 

 

 

멀티스레드 기본소스

//ver 0.1.2
using UnityEngine;
using System.Collections;
using System.Threading; //스레드 시스템을 호출
using System; //스레드에서 계산을 위해 닷넷 시스템 호출

public class multi_thread : MonoBehaviour {
 private Thread[] _thread;
 private EventWaitHandle[] _thread_sig;
 private EventWaitHandle _thread_sig_main ;
 private EventWaitHandle _thread_sig_end ;
 public int _core_num = SystemInfo.processorCount*16; //코어갯수 설정(코어갯수*16)
 private int i, j, k, l; //반복문용 변수 설정
 // Use this for initialization
 void Awake() {

  _thread = new Thread[_core_num];  //코어갯수에 맞게 스레드 생성
  _thread_sig = new EventWaitHandle[_core_num];  //코어갯수에 맞게 핸들생성



  _thread_sig_main=new EventWaitHandle(false,EventResetMode.ManualReset);  //메인스레드 처리 완료 알림 시그널 생성
  _thread_sig_end=new EventWaitHandle(false,EventResetMode.ManualReset);  //메인스레드 수신완료 시그널 생성
  for(i=0;i<_core_num;i++)
  {
   _thread_sig[i]=new EventWaitHandle(false,EventResetMode.ManualReset);//서브스레드 대기 시그널 생성
   _thread[i] = new Thread (subthread); //스레드를 생성
   _thread[i].IsBackground = true; //백그라운드에서 동작(메인스레드의 하위로 들어감)
   //_thread[i].Priority = ThreadPriority.Highest;  //백그라운드 스레드의 우선순위를 높음으로 변경(높을수록 빠름)
   //_thread[i].Priority = ThreadPriority.AboveNormal;  //백그라운드 스레드의 우선순위를 약간 높음으로 변경
   //_thread[i].Priority = ThreadPriority.Normal;  //백그라운드 스레드의 우선순위를 보통으로 변경
   _thread[i].Priority = ThreadPriority.BelowNormal;  //백그라운드 스레드의 우선순위를 약간 낮음으로 변경
   //_thread[i].Priority = ThreadPriority.Lowest;  //백그라운드 스레드의 우선순위를 낮음으로 변경(낮을수록 느림)
   _thread[i].Start (i); //스레드 시작
  }
 }
 // Update is called once per frame
 void LateUpdate ()   
 {
  _thread_sig_end.Reset();//수신완료 리셋
  _thread_sig_main.Set();//메인스레드 처리 완료 알림(서브스레드 시작)
  for (i=0; i<_core_num; i++) 
  {
   _thread_sig[i].WaitOne();//서브스레드 처리 완료 대기중
  }
  _thread_sig_main.Reset();//메인스레드 처리중 알림
  _thread_sig_end.Set();//메인스레드 수신 완료 알림
 }
 private void subthread(object _thread_num)
 {
  int _t_thread_num=(int)_thread_num; //스레드 번호 인자를 넘겨받은것을 언박싱
  
  while(true)
  {
   _thread_sig_main.WaitOne(); //메인스레드가 종료할때까지 대기

   /*
   여기에 처리시킬 코드를 넣습니다 
   예시
   for (int i=_t_thread_num; i<100000; i+=_core_num) 
   {
    _t += i;
   }
    */


   _thread_sig[_t_thread_num].Set(); //서브스레드 종료알림
   _thread_sig_end.WaitOne(); //메인스레드가 수신했는지
   _thread_sig[_t_thread_num].Reset(); //서브스레드 재가동 알림
 }
}

 

 

일반함수처럼 쓸수있는 스레드. (태스크)

test(); 같은식으로 호출해주면 됨

비동기로 작동한다

주의점은 유니티가 종료되어도 계속 작동해서 가급적 코루틴을 쓰자

async void test()
{
    await Task.Run(() => {
        while (true)
        {
            System.Threading.Thread.Sleep(1000);
            Debug.Log($"테스트 {System.DateTime.Now}");
        }
    });
}

 

 

태스크, 코루틴이랑 비슷하지만 유니티가 종료되어도 계속 작동한다

유니티 함수계열은 안 된다(디버그로그는 된다)

var t = System.Threading.Tasks.Task.Run(() => {
    //System.Threading.Tasks.Task.Delay(10000).Wait();
    System.Threading.Thread.Sleep(10000);
    Debug.Log("Task ended delay...");
});

 

 

반환값이 있는 태스크

주의점은 result호출시 계산이 끝날때까지 기다린다

Debug.Log($"Start {System.DateTime.Now}");

var t = System.Threading.Tasks.Task.Run(() => {
    System.Threading.Thread.Sleep(10000);
    Debug.Log($"Task ended delay... {System.DateTime.Now}");
});



var t2 = System.Threading.Tasks.Task.Run(() => {
    System.Threading.Thread.Sleep(3000);
    return System.DateTime.Now;
});
Debug.Log($"Task2 ended delay...{t2.Result}"); //result구하면서 wait가 걸린다

'윈도우폼' 카테고리의 다른 글

윈폼 키보드마우스  (0) 2021.01.17
자주 쓰는 윈폼 코드 모음  (0) 2020.10.31
c# 윈도우 폼  (0) 2018.01.28
posted by 모카쨩
2020. 10. 31. 09:56 윈도우폼

 

 

윈폼의 Debug로그이다.

System.Diagnostics.Debug.WriteLine("디버그 메세지");

 

팝업띄우는 버전

System.Windows.Forms.MessageBox.Show("디버그 메세지");

 

 

윈폼 리퀘스트

//v2
public static string DownloadText(string url)
{
    try
    {
        var webClient = new System.Net.WebClient();
        return webClient.DownloadString(url);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        return null;
    }
}

//v1
/*
public static string DownloadText(string url)
{
    try
    {
        var webClient = new System.Net.WebClient();
        var response = webClient.OpenRead(url);
        using (var streamReader = new System.IO.StreamReader(response))
        {
            string result = streamReader.ReadToEnd();
            streamReader.Close();
            return result;
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        return null;
    }
}
*/

 

 

현재 컴퓨터 유저 이름을 반환합니다. 

System.Environment.UserName

 

 

 

 

 

Lerp

double Lerp(double a,double b,double t)
{
    //return a*(1.0-t)+b*t;
    return a + (b - a)* t;
}
Vector3 Lerp(Vector3 a, Vector3 b, float t)
{
    return a + (b - a)* t;
}

 

 

 

새창 띄울때

var form = Application.OpenForms[nameof(Form2_Prediction)];
if (form==null)
{
    form = new Form2_Prediction();
    form.Show();
}
else
{
    form.Activate();
}

 

 

 

프로세스 확인 (unity가 켜져있는지 확인하는 코드이다)

var processes=System.Diagnostics.Process.GetProcesses();
var processesNames = System.Array.ConvertAll(processes, x => x.HasExited ?"": x.ProcessName).ToList();
processesNames = processesNames.GroupBy(x=>x).Select(x=>x.First()).ToList();
processesNames = processesNames.FindAll(x => string.IsNullOrWhiteSpace(x) == false);
processesNames = processesNames.FindAll(x => x.ToLower().Contains("unity"));
foreach (var processesName in processesNames)
{
    Debug.Log(processesName);
}

 

 

콤보박스에 Enum 할당

var ProportionalOptionNames = System.Enum.GetNames(typeof(ProportionalOption));
ProportionalOptionBoxs[i].Items.AddRange(ProportionalOptionNames);

 

 

 

window form

.net

닷넷

'윈도우폼' 카테고리의 다른 글

윈폼 키보드마우스  (0) 2021.01.17
c# 멀티스레드 기본소스  (0) 2020.11.23
c# 윈도우 폼  (0) 2018.01.28
posted by 모카쨩
2018. 1. 28. 17:19

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.


저사양 유저용 블로그 진입