스레드 생성

DWORD WINAPI ThreadFunc(LPVOID temp)

{

printf("dd");

return 0;

}


void main()

{

HANDLE hHandle;

DWORD ThreadID;


hHandle = CreateThread(NULL, 0, ThreadFun, NULL, 0 &ThreadID);


Sleep(10000)

}

정규식 표현

#include <iostream>

#include <string>

#include <boost/regex.hpp>  // Boost.Regex lib

#include <fstream>


using namespace std;

const int BUFSIZE = 10000;


int main(int argc, char ** argv ) 

{

string s, sre;

boost::regex re;

boost::cmatch matches;


cout << "Expression : ";

cin >> sre;


cout <<"str: ";

cin >> s;


try

{

re = sre;

}

catch(boost::regex_error& e)

{

cout << sre << "is not a valid regular expression : " << e.what() << endl;

// continue;

}

if(boost::regex_match(s.c_str(), matches, re))

{

for(int i = 0; i<matches.size(); i++)

{

string match(matches[i].first, matches[i].second);

cout <<"\tmatches[" <<i << "] \ " <<match <<endl;

}

}

else

{

cout << "The regexp \"" << re << "\" does not mach \"" << s <<"\"" <<endl;

}

}


'c/c++' 카테고리의 다른 글

c++ 관리자 권한으로 프로그램 실행시키는 방법  (0) 2014.03.03
스레드 생성  (0) 2013.04.05
스레드 생성  (0) 2013.03.26
MMF(Memory Mapping File) & Shared Memory  (0) 2013.03.26
JSON 사용하기  (0) 2013.03.13

스레드 생성


#include <windows.h>

#include <process.h>

#include <iostream>


using namespace std;


#define MAX_THREAD  2


DWORD WINAPI ThFunc(LPVOID lpParam)

{

    int n;

    printf("[%d] address of 'n' is %p\n", _threadid, &n);

    printf("[%d] exit\n", _threadid);

    return 0;

}


int main(int argc, char **argv)

{

    int i = 0, nData = 100;

    DWORD dwThID[MAX_THREAD];

    HANDLE hThreads[MAX_THREAD];

    unsigned long ulStackSize = 0;


    memset(dwThID, 0, sizeof(dwThID)/sizeof(dwThID[0]));

    memset(hThreads, 0, sizeof(hThreads)/sizeof(hThreads[0]));


    for ( i = 0; i < MAX_THREAD; i++ )

    {

        hThreads[i] = CreateThread(NULL, ulStackSize, ThFunc, &nData, CREATE_SUSPENDED, &dwThID[i]);

        printf("[%d] start\n", (int)dwThID[i]);

        SetThreadPriority(hThreads[i], THREAD_PRIORITY_HIGHEST);

        printf("[%d] thread priority is %d\n", dwThID[i], GetThreadPriority(hThreads[i]));

        ResumeThread(hThreads[i]);

    }


    WaitForMultipleObjects(MAX_THREAD, hThreads, TRUE, INFINITE);

    printf("thread working is done.\n");


    for ( i = 0; i < MAX_THREAD; i++ )

        CloseHandle(hThreads[i]);


    return 0;

}

'c/c++' 카테고리의 다른 글

스레드 생성  (0) 2013.04.05
정규식 표현  (0) 2013.03.27
MMF(Memory Mapping File) & Shared Memory  (0) 2013.03.26
JSON 사용하기  (0) 2013.03.13
ip/ mac 주소 얻기  (0) 2013.02.25

MMF(Memory Mapping File) & Shared Memory

MMF 랑 Shared Memory랑 다른 건가? 

싶어서 검색 ㄱㄱ


"MMF를 이용하여 Shared Memory를 구현한다"

를 보고 둘이 다른 것임을 알았다



MMF = FILE MAPPING이고, 

파일을 메모리에 연결 하여 메모리에 입출력 하는  것


FILE 을 메모리에 올려 사용하는 것도 포함 (프로세스 <-> 파일)

1. CreatFile()

2. CreateFileMapping

3. MapViewOfFile()


공유 메모리를 이용하여 사용하는 것도 포함( 프로세스 <-> 프로세스 ) 

1. CreateFileMapping()

2. MapviewOfFile()



맞나?ㅠㅠ



'c/c++' 카테고리의 다른 글

정규식 표현  (0) 2013.03.27
스레드 생성  (0) 2013.03.26
JSON 사용하기  (0) 2013.03.13
ip/ mac 주소 얻기  (0) 2013.02.25
서비스  (0) 2013.02.25

JSON 사용하기

1.     Json 관련 헤더 파일 포함

A.     autolink.h

B.      config.h

C.      features.h

D.     json.h

E.      json_batchallocator.h

F.      json_internalarray.inl

G.     json_internalmap.inl

H.     json_valuiterator.inl

I.       reder.h

J.       value.h

K.      writer.h

 

2.     소스 파일 포함

A.     json_reader.cpp

B.      json_value.cpp

C.      json_writer.cpp

 

3.     사용 방법

A.     데이터 저장

{       Json::Value root;

        Json::Value encoding;

 

        root["encoding"] = "UTF-8";

 

        Json::Value plugins;

        plugins.append("python");

        plugins.append("C++");

        plugins.append("ruby");

        plugins.append(test);

        root["plub-ins"] = plugins;

 

        Json::Value indent;

        indent["length"] = 3;

        indent["use_space"] = true;

        root["indent"] = indent;

 

        Json::StyledWriter writer;

        std::string outputConfig = writer.write( root );

}

 

 

 

 

'c/c++' 카테고리의 다른 글

스레드 생성  (0) 2013.03.26
MMF(Memory Mapping File) & Shared Memory  (0) 2013.03.26
ip/ mac 주소 얻기  (0) 2013.02.25
서비스  (0) 2013.02.25
const 과 #define  (0) 2013.01.30

ip/ mac 주소 얻기

const char* get_mac()

{

DWORD dwRetVal = 0;

PIP_ADAPTER_INFO pai = 0;

ULONG* pul = 0;


static char buf [20] ={};


ULONG ulOutBufLen = sizeof (IP_ADAPTER_INFO);

pai = (IP_ADAPTER_INFO *)calloc(sizeof (IP_ADAPTER_INFO), 1);

if (pai == NULL) {

printf( "Error allocating memory needed to call GetAdaptersinfo\n");

return 0;

}


if (GetAdaptersInfo(pai, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {

pul = new ULONG[ulOutBufLen];

pai = PIP_ADAPTER_INFO(pul);

if (pai == NULL) {

printf( "Error allocating memory needed to call GetAdaptersinfo\n");

return 0;

}

}

if ((dwRetVal = GetAdaptersInfo(pai, &ulOutBufLen)) == NO_ERROR) 

{

while( pai )

{

if( strcmp( pai->IpAddressList.IpAddress.String, "0.0.0.0" ))

break;


pai = pai->Next;

}


BYTE addr [MAX_ADAPTER_ADDRESS_LENGTH] = {};



if(pai)

{

memcpy (addr, pai->Address, sizeof (addr));

sprintf_s( buf, sizeof(buf), "%0.2X-%0.2X-%0.2X-%0.2X-%0.2X-%0.2X", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5] );

}



if(pul)

delete [] pul;

}else{


printf( "Failed to get an AdapterInfo!" );

if(pai)

free(pai);

return 0;

}

return buf;


}


void get_ip()

{

WORD wVersionRequested;

WSADATA wsaData;


char name[255]= {0,};

CString ip;


PHOSTENT hostinfo;

wVersionRequested = MAKEWORD(2,0);


try{

if(WSAStartup(wVersionRequested, & wsaData))

throw WSAGetLastError();

if( gethostname(name, sizeof(name)) || !(hostinfo = gethostbyname(name)))

throw WSAGetLastError();


ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);

printf("\n ip : %s \n", ip.GetString());


WSACleanup();


}

catch(int n)

{

WSACleanup();

printf("WSAGetLastError : %d\n",n);

}

}

'c/c++' 카테고리의 다른 글

MMF(Memory Mapping File) & Shared Memory  (0) 2013.03.26
JSON 사용하기  (0) 2013.03.13
서비스  (0) 2013.02.25
const 과 #define  (0) 2013.01.30
구조체  (0) 2013.01.30

서비스

서비스의 종류

  • 윈도우 서비스    SDK
  • 드라이버 서비스    DDK




- 현재 문제점

  1.  드라이버 서비스 설치
  2.  서비스 설치가 되면 모든 계정에서도 설치가 되는가 
  3.  서비스를 설치하는데 권한이 필요
- 고려할점
계정에 비밀번호를 적용하지 않은 사용자 


'c/c++' 카테고리의 다른 글

JSON 사용하기  (0) 2013.03.13
ip/ mac 주소 얻기  (0) 2013.02.25
const 과 #define  (0) 2013.01.30
구조체  (0) 2013.01.30
함수에서 값을 반환하는 방법  (0) 2013.01.18

API _ 선, 박스, 도형 그리기

출처

http://blog.naver.com/PostView.nhn?blogId=eunbear1030&logNo=70033469547&redirect=Dlog&widgetTypeCall=true

]선(라인)그리기

MoveToEx와 LineTo라는 두 개의 함수를 쌍으로 사용

MoveToEx함수는 그리는 시작점으로 그리기 좌표를 이동시키는 기능

LineTo함수는 MoveToEx함수를 실행한 후에 그 위치부터 라인을 그리고자 할때 사용

 

BOOL MoveToEx( 
HDC hdc, // 디바이스 컨텍스트 핸들
int X, // 새로운 위치의 x좌표
int Y, // 새로운 위치의 y자표
LPPOINT lpPoint // 이전 위치 좌표
);

 

BOOL LineTo( 
HDC hdc, // 디바이스 핸들
int nXEnd, // 그리는 좌표 종점 x
int nYEnd // 그리는 좌표 종점 y
);

 

]박스 그리기

박스를 그리는 함수 중 중요한 함수는 2개

  1. Rectangle함수 - 일반적인 박스를 그리는 함수
  2. RoundRect 함수 - 모서리가 둥근 박스를 그리는 함수

BOOL Rectangle( 
HDC hdc, // 디바이스 컨텍스트 핸들 
int nLeftRect, // 좌측 x좌표
int nTopRect, // 상단 y좌표
int nRightRect, // 우측 x좌표
int nBottomRect //하단 y좌표
);

BOOL RoundRect( 
HDC hdc, // 디바이스 컨텍스트 핸들
int nLeftRect, // 좌측 x좌표
int nTopRect, // 상단  y좌표
int nRightRect, // 우측 x좌표
int nBottomRect, // 하단 y좌표
int nWidth, // 모서리의 가로측 지름
int nHeight // 모서리의 세로측 지름
); 

]다양한 원 그리기

  1. Ellipse함수 - 설정한 박스영역에 맞는 원을 그려줌
  2. Arc함수 - 설정된 영역에 그리기 시작좌표 (x,y)에서 종료지점 (x,y)까지 원호를 그려줌
  3. Chord함수 - 현을 그려줌
  4. Pie함수 - 부채꼴을 그려줌

BOOL Ellipse( 
HDC hdc, // handle to device context 
int nLeftRect, // 좌측 x좌표
int nTopRect, // 상단 y좌표
int nRightRect, // 우측 x좌표
int nBottomRect // 하단 y좌표

);

BOOL Arc( 
HDC hdc, // 디바이스 컨텍스 핸들 
int nLeftRect, // 좌측 x좌표
int nTopRect, // 상단 y좌표
int nRightRect, // 우측 x좌표
int nBottomRect, // 하단 y좌표
int nXRadial1, // 그리기를 시작하는 x지점
int nYRadial1, // 그리기를 시작하는 y지점
int nXRadial2, // 그리기를 종료하는 x지점
int nYRadial2 // 그리기를 종료하는 y지점
);

BOOL Chord( 
HDC hdc, // 디비이스 컨텍스 핸들
int nLeftRect, // 좌측 x좌표
int nTopRect, // 상단 y좌표
int nRightRect, // 우측 x좌표
int nBottomRect, //하단 y좌표 
int nXRadial1, // 그리기를 시작하는 x지점
int nYRadial1, // 그리기를 시작하는 y지점
int nXRadial2, // 그리기를 종료하는 x지점
int nYRadial2 // 그리기를 종료하는 y지점

);

BOOL Pie( 
HDC hdc, // 디비이스 컨텍스 핸들
int nLeftRect, // 좌측 x좌표
int nTopRect, // 상단 y좌표
int nRightRect, // 우측 x좌표
int nBottomRect, //하단 y좌표 
int nXRadial1, // 그리기를 시작하는 x지점
int nYRadial1, // 그리기를 시작하는 y지점
int nXRadial2, // 그리기를 종료하는 x지점
int nYRadial2 // 그리기를 종료하는 y지점

);


]다각형과 poly Line

다각형은 여러점을 연결하는 도형을 의미, Poly Line은 여러점에 직선을 연결한 것을 의미

 

Polygon함수 - 다각형을 그릴때 이용

Polyline함수 - Poly Line을 그릴때 이용

 

BOOL Polyline( 
HDC hdc, // 디바이스 컨텍스트 핸들
CONST POINT *lppt, // 그릴 좌표
int cPoints // 좌표의 수
); 
BOOL Polygon( 
HDC hdc, // 디바이스 컨텍스트 핸들
CONST POINT *lppt, // 그릴 좌표
int cPoints // 좌표의 수
); 

]베지어 곡선 그리기

베지어곡선은 설정해준 최소 3개의 점 사이로 곡선이 그려지는 것을 의미, PolyBezier함수를 이용

 

BOOL PolyBezier( 
HDC hdc, // 디바이스 컨텍스트 핸들
CONST POINT *lppt, // 그릴 좌표
int cPoints // 좌표의 수
); 

*` 소스 *

 

#include <windows.h>


LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
static char szAppName[] = "DrawEx" ;
HWND        hwnd ;
MSG         msg ;
WNDCLASSEX  wndclass ;

 

wndclass.cbSize        = sizeof (wndclass) ;
wndclass.style         = CS_HREDRAW | CS_VREDRAW ;
wndclass.lpfnWndProc   = WndProc ;
wndclass.cbClsExtra    = 0 ;
wndclass.cbWndExtra    = 0 ;
wndclass.hInstance     = hInstance ;
wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
wndclass.lpszMenuName  = NULL ;
wndclass.lpszClassName = szAppName ;
wndclass.hIconSm       = LoadIcon (NULL, IDI_APPLICATION) ;

 

RegisterClassEx (&wndclass) ;

 

hwnd = CreateWindow (szAppName,     
"기본그리기예제:DrawEx",   
WS_OVERLAPPEDWINDOW,  
CW_USEDEFAULT,        
CW_USEDEFAULT,        
CW_USEDEFAULT,        
CW_USEDEFAULT,        
NULL,                 
NULL,                 
hInstance,            
NULL) ;           

 

ShowWindow (hwnd, iCmdShow) ;
UpdateWindow (hwnd) ;

 

while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
return msg.wParam ;
}

 

LRESULT CALLBACK WndProc (HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
HDC         hdc ;
PAINTSTRUCT ps ;
RECT rect;
POINT prevpos;
POINT pline[6]={50,133,146,99,246,133,247,212,58,216,50,133};
POINT pgon[4]={308,120,440,118,380,212,308,120};

 

switch (iMsg)
{
case WM_CREATE :
return 0 ;

case WM_PAINT :
hdc = BeginPaint (hwnd, &ps) ;
GetClientRect(hwnd,&rect);
//박스 그리기
Rectangle(hdc,rect.left+10,rect.top+10,rect.right-10,rect.bottom-10);
//라운드 박스 그리기    
RoundRect(hdc,rect.left+20,rect.top+20,rect.right-20,rect.bottom-20,20,20);
//원 그리기
Ellipse(hdc,rect.left+30,rect.top+30,rect.right-30,rect.bottom-30);
Arc(hdc,0,0,100,100,50,0,100,50);
//직선 그리기
MoveToEx(hdc,rect.left+10,rect.top+10,&prevpos);
LineTo(hdc,rect.right-10,rect.bottom-10);
//베지어 곡선
PolyBezier(hdc,pline,4);
//폴리 라인
Polyline(hdc,pline,6);
//다각형
Polygon(hdc,pgon,4);
EndPaint (hwnd, &ps) ;
return 0 ;

case WM_DESTROY :
PostQuitMessage (0) ;
return 0 ;
}

return DefWindowProc (hwnd, iMsg, wParam, lParam) ;
}

 

*`출력 결과*

 


Win32 프로젝트를 빈프로젝트로 생성하여 DialogBox 띄우기

#include <Windows.h>

#include "resource.h"


BOOL CALLBACK MainDlgProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam);

HINSTANCE g_hInst;

HWND hDlgMain, hStatic;


int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParma, int nCmdShow)

{

g_hInst = hInstance;


DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG1), HWND_DESKTOP, MainDlgProc);


return 0;

}


BOOL CALLBACK MainDlgProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam)

{

switch(iMessage)

{

case WM_INITDIALOG:

//SetWindowPos(hDlg, HWND_TOP, 100, 100, 0,0,SWP_NOSIZE);

break;

case WM_COMMAND:

switch(LOWORD(wParam))

{

case IDOK:

case IDCANCEL:

EndDialog(hDlgMain, 0);

return TRUE;

}

return FALSE;

case WM_CLOSE:

PostQuitMessage(0);

return TRUE;

}


return FALSE;

}

활성화된 화면 캡쳐 ScreenCapture


HBITMAP ScreenCapture(HWND hWnd)

{


HDC hScrDC, hMemDC;

HBITMAP hBitmap;

RECT rt;


GetWindowRect(GetForegroundWindow(), &rt);

// GetWindowRect(GetActiveWindow(), &rt);


rt.left = max(0, rt.left);

rt.right = min(rt.right, GetSystemMetrics(SM_CXSCREEN));

rt.top = max(0, rt.top);

rt.bottom = min(rt.bottom, GetSystemMetrics(SM_CYSCREEN));


hScrDC=CreateDC("DISPLAY",NULL,NULL,NULL);


hMemDC = CreateCompatibleDC(hScrDC);


hBitmap = CreateCompatibleBitmap(hScrDC, rt.right-rt.left, rt.bottom-rt.top);


SelectObject(hMemDC, hBitmap);


BitBlt(hMemDC, 0, 0, rt.right-rt.left, rt.bottom-rt.top, hScrDC, rt.left, rt.top, SRCCOPY);


DeleteDC(hMemDC);

DeleteDC(hScrDC);

InvalidateRect(hWnd, NULL, TRUE);


return hBitmap;

}


==================================================================================================

위의 함수를 호출하여 사용한다

핫키를 등록하여 Ctrl + F4가 눌리면 화면 캡쳐!

WM_PAINT에서 캡쳐된 화면을 그려줌 

case WM_CREATE:

RegisterHotKey(hWnd, 0, MOD_CONTROL, VK_F4);

break;


case WM_HOTKEY:

hBit = ScreenCapture(hWnd); // CTRL +F4

return 0;


case WM_PAINT:

hdc = BeginPaint(hWnd, &ps);

if(hBit != NULL) 

{

hMemDC = CreateCompatibleDC(hdc);

SelectObject(hMemDC, hBit);

GetObject(hBit, sizeof(BITMAP), &bmp);

BitBlt(hdc, 0, 0, bmp.bmWidth, bmp.bmHeight, hMemDC, 0, 0, SRCCOPY);

DeleteDC(hMemDC);

}

EndPaint(hWnd, &ps);


return 0;


====================================================================================