반응형

Test class declares Change() as a friend function and it accesses the private member variable 'a'.

아래 코드에서 Test 클래스는 Change라는 friend 함수를 선언 하고 멤버 변수 a에 접근한다.


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
#include <iostream>
 
using namespace std;
 
class Test
{
private:
    int a;
 
public:
    Test() { a = 0; }
    ~Test() { }
    void Show() { cout << "a: " << a << endl; }
 
    friend void Change(Test& t, int c);
};
 
void Change(Test& t, int c)
{
    t.a = c;
}
 
int main(int argc, char* argv[])
{
    Test t;
    t.Show();
    Change(t, 10);
    t.Show();
 
    return 0;
}
cs


How to set default arguments in a friend function?

friend 함수 Change에 디폴트 매개 변수를 설정하고 싶다면 어떻게 해야 할까?

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
#include <iostream>
 
using namespace std;
 
class Test
{
private:
    int a;
 
public:
    Test() { a = 0; }
    ~Test() { }
    void Show() { cout << "a: " << a << endl; }
 
    friend void Change(Test& t, int c = 100);
};
 
void Change(Test& t, int c)
{
    t.a = c;
}
 
int main(int argc, char* argv[])
{
    Test t;
    t.Show();
    Change(t, 10);
    t.Show();
 
    return 0;
}
cs



Setting default arguments in the friend function declaration will cause an error message like below.

위 코드와 같이 friend 선언부에 디폴트 매개 변수를 설정 하면 별 문제 없이 빌드는 되지만 아래와 같은 메세지가 나타나게 된다.

friend declaration cannot add default arguments to previous declaration


Try to set default arguments in the function definition.

아래와 같이 함수 정의부에 디폴트 매개 변수를 설정 하면 에러 메세지가 나타나지 않는다.

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
#include <iostream>
 
using namespace std;
 
class Test
{
private:
    int a;
 
public:
    Test() { a = 0; }
    ~Test() { }
    void Show() { cout << "a: " << a << endl; }
 
    friend void Change(Test& t, int c);
};
 
void Change(Test& t, int c = 100)
{
    t.a = c;
}
 
int main(int argc, char* argv[])
{
    Test t;
    t.Show();
    Change(t, 10);
    t.Show();
 
    return 0;
}
cs


Or, you can declare and define the friend function and set the default arguments at once.  

아니면 friend 함수 선언부에서 함수 정의까지 작성하고 매개 변수를 설정해 준다.

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
#include <iostream>
 
using namespace std;
 
class Test
{
private:
    int a;
 
public:
    Test() { a = 0; }
    ~Test() { }
    void Show() { cout << "a: " << a << endl; }
 
    friend void Change(Test& t, int c = 100)
    {
        t.a = c;
    }
};
 
int main(int argc, char* argv[])
{
    Test t;
    t.Show();
    Change(t, 10);
    t.Show();
 
    return 0;
}
cs


<Result>


반응형
Posted by J-sean
:
반응형

Color Picker will be very useful if you are working as a Web Developer or UI designer, who mainly uses Visual Studio for the day to day assignments. This tool provides a color tool window, color swatcher in the editor.


This tool offers the below options,

  • Highlight colors in Visual Studio Document Editor (".css", ".scss", ".less", ".asp", ".aspx", ".htm", ".html", ".cshtml", ".vbhtml", ".xaml" are enabled by default), Additional Parsing, Customize using Tools-Options-ColorPicker.
  • Edit color using double click from any enabled file (editor)
  • Insert colors to any active text document
  • Color Selection from Color Canvas.
  • Color Selection from Available Colors.
  • Color Selection from Standard Colors.
  • Color Selection from Saved Colors.
  • Color Selection using Eyedropper.
  • Copy\Paste Color codes (Name, #HEX, rgb, rgba, hsl, hsla, hsb\hsv, cmyk). rgb and rgba are offered in different formats
  • Selected colors Tints & Shades.
  • Color code comparison of Orginal and New.

Visual Studio에서 원하는 색상 코드를 확인 할 수 있는 Extenstion 입니다.

색깔의 이름으로 검색하거나 코드를 색깔로, 색깔을 코드로 변환할 수도 있고 찾은 색을 저장 하거나 소스 코드에 바로 삽입하는 등의 기능이 지원 됩니다.


Tools - Extensions and Updates...


Click 'Online' tab and search 'color picker'.


Close Visual Studio.


Click 'Modify' button on VSIX installer.


It starts installing.


Click 'Close' button.


Tools - Color Picker




Click 'Color Eyedropper'. Or you can enter any name of the colors into the edit box, e.g., red, blue, green, or etc.


Move the mouse cursor and click on the color you want.


Color Picker shows the color and its codes.


You can change the format by clicking on the code format.


Click the check button and insert the color code into your source.


Tools - Options...


Color Picker - General - You can change options.



반응형
Posted by J-sean
:
반응형

'Open Command Line' opens a command line at the root of the project. Support for all consoles such as CMD, PowerShell, Bash, etc. Provides syntax highlighting, Intellisense and execution of .cmd and .bat files.


This extension adds a new command to the project context menu that will open a command prompt on the project's path. If the solution node is selected in Solution Explorer, then a console will open at the root of the .sln file.


Open Command LIne은 작업 중인 Visual Studio 프로젝트 폴더에서 바로 command prompt를 열 수 있게 해주는 extension 입니다.

CMD, PowerShell, Bash등을 지원합니다.


Run Tools - Extensions and Updates...


Search 'Open Command Line' on Online tab and click Download.


Installation starts when Visual Studio closes.


Close Visual Studio and click Modify on VSIX Installer.


Install it.


Click Close.




Right-click on Solution Explorer - Open Command Line - Default(cmd) (Shortcut: Alt + Space)


Command Prompt opens on the project's path.


Right-click on Solution Explorer - Open Command Line - Settings...


You can change settings.




반응형
Posted by J-sean
:
반응형

Explains how to make a game(Prince of Persia) save file editor with C++.

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
#include <iostream>
#include <fstream>
 
using namespace std;
 
int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        cout << "Usage : " << argv[0<< " [save file name] [energy]" << endl;
        cout << "Example: " << argv[0<< " prince.sav 8" << endl;
        return -1;
    }
 
    short value = atoi(argv[2]); // 2 byte value (for 16 bit old dos game)
 
    ofstream fout(argv[1], ios_base::binary | ios_base::out | ios_base::in);
    if (!fout.is_open())
    {
        cout << "Can't find " << argv[1<< endl;
        return -1;
    }
 
    fout.seekp(0x06, ios_base::beg); // Prince's energy saved at 0x06~0x07 (2 byte)
    fout.write((char*)& value, sizeof(short)); // 2 byte
 
    fout.close();
 
    cout << "Success!" << endl;
 
    return 0;
}
cs






반응형
Posted by J-sean
:
반응형

2021.09.25 - [C, C++] - Qt6 설치 및 간단한 사용법

 

Qt의 Pixmap을 이용해 간단한 스프라이트 애니매이션을 구현 할 수 있다.

 

아래와 같은 스프라이트 이미지를 준비 한다. 

horse.zip
다운로드

이 중 처음 11개의 달리는 이미지 프레임만 사용한다.

 

 

Qt Widgets Application으로 기본 설정들을 적용해서 프로젝트를 만든다. (D:\Horse)

 

 

프로젝트를 만든 후 바로 build 디렉토리가 만들어지지 않으므로 build를 한 번 진행 한다.

 

build 디렉토리에 준비한 스프라이트 이미지를 복사한다.

 

mainwindow.h 에 아래와 같이 추가 한다.

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
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include <QTimer>
#include <QPainter>
#include <QDebug>
 
namespace Ui {
class MainWindow;
}
 
class Sprite
{
public:
    Sprite(QSize winsize);
    void Draw(QPainter* painter);   // 현재 프레임 그리기
    void NextFrame();   // 다음 프레임 지정
 
private:
    QPixmap* SpriteImage;   // 스프라이트
    int CurrentFrame;   // 현재 프레임
    int TotalFrame; // 전체 프레임 수(11)
    int Column; // 스프라이트내 프레임 열(4)
    int Row;    // 스프라이트내 프레임 행(3) (실제 사용되지는 않음)
    int FramesizeX; // 한 프레임의 X 길이(128)
    int FramesizeY; // 한 프레임의 Y 길이(128)
    QPoint FramePosition;   // 스프라이트내 현재 프레임의 픽셀 단위 위치
    QPoint DrawPosition;    // 윈도우에서 프레임이 그려질 위치
    QSize MainWindowSize;   // 윈도우 사이즈
};
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
 
    virtual void paintEvent(QPaintEvent* event);
 
private:
    Ui::MainWindow *ui;
 
    Sprite* sprite; // 스프라이트
    QTimer* timer;  // 타이머
};
 
#endif // MAINWINDOW_H
cs

 

 

mainwindow.cpp 에 아래와 같이 추가 한다.

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
#include "mainwindow.h"
#include "ui_mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
 
    sprite = new Sprite(this->size());
    timer = new QTimer(this);
    timer->start(50);   // 20Hz 타이머 시작
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));    // timeout() 시그널이 발생하면 update() 실행
    // connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
    // Creates a connection of the given type from the signal in the sender object to the method in the receiver object.
    // Returns a handle to the connection that can be used to disconnect it later. You must use the SIGNAL() and SLOT() macros
    // when specifying the signal and the method.
}
 
MainWindow::~MainWindow()
{
    delete timer;
    delete sprite;
 
    delete ui;
}
 
void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter paint(this);   // The QPainter class performs low-level painting on widgets and other paint devices.
    sprite->Draw(&paint);
    sprite->NextFrame();
}
 
// 128X128 사이즈, 4X3배열의 11개 프레임
Sprite::Sprite(QSize winsize) : CurrentFrame(0), TotalFrame(11), Column(4), Row(3), FramesizeX(128), FramesizeY(128), FramePosition(00)
{
    MainWindowSize = winsize;   // 메인 윈도우 사이즈
    qDebug() << "Main Window Size: " << MainWindowSize << endl// Application Output 창에 메인 윈도우 사이즈(400X300) 출력
    SpriteImage = new QPixmap("horse.png"); //The QPixmap class is an off-screen image representation that can be used as a paint device.
    qDebug() << "Sprite Size: " << SpriteImage->size() << endl;    // Application Output 창에 스프라이트 사이즈(512X1024) 출력
 
    // 메인 윈도우 중앙에 프레임 출력
    DrawPosition.setX(MainWindowSize.width() / 2 - FramesizeX / 2);
    DrawPosition.setY(MainWindowSize.height() / 2 - FramesizeY / 2);
}
 
void Sprite::Draw(QPainter* painter)
{
    // Draws a pixmap at (x, y) by copying a part of the given pixmap into the paint device.
    painter->drawPixmap(DrawPosition.x(), DrawPosition.y(), *SpriteImage, FramePosition.x(), FramePosition.y(), FramesizeX, FramesizeY);
 
    // 'Running horse' 문자열 출력
    const QRect rect = QRect(00, MainWindowSize.width(), MainWindowSize.height() / 2);
    painter->setPen(Qt::blue);
    painter->setFont(QFont("Arial"30));
    painter->drawText(rect, Qt::AlignCenter, "Running horse");
}
 
void Sprite::NextFrame()
{
    if (CurrentFrame >= TotalFrame) // 11번 째 프레임을 넘어가면 0으로 초기화
        CurrentFrame = 0;
 
    // 출력할 프레임의 픽셀 단위 위치 지정
    FramePosition.setX((CurrentFrame % Column) * FramesizeX);
    FramePosition.setY((CurrentFrame / Column) * FramesizeY);
 
    CurrentFrame++;
}
cs

 

프로젝트를 build하고 실행하면 아래와 같은 애니매이션이 재생된다.

 

Application Output 창에는 Main Window와 Sprite 사이즈가 표시 된다.

 

iCCP 관련 warning은 무시하거나 이 링크를 참고해서 제거한다.

 

 

반응형
Posted by J-sean
:
반응형

2021.09.25 - [C, C++] - Qt6 설치 및 간단한 사용법

2021/02/13 - [C, C++] - Linux(Ubuntu) Qt5 Image Display - 리눅스(우분투) Qt5 이미지 디스플레이

2021/02/12 - [C, C++] - Linux(Ubuntu) Qt5 GUI Programming - 리눅스(우분투) Qt5 GUI 프로그래밍

 

Qt는 GUI 프로그램 개발에 널리 쓰이는 크로스 플랫폼 프레임워크이다. 홈페이지에서 Open Source 버전을 다운 받아 실행 한다.

 

기본설정에서 MSVC 2017 64-bit만 추가한다.

 

Qt 설치가 완료되면 Visual Studio에서도 사용 할 수 있도록 Extension을 설치 한다.

 

Online에서 qt를 검색해 Qt Visual Studio Tools를 설치한다.

 

설치가 완료되면 Qt Options를 선택 한다.

 

 

Qt가 설치된 위치의 msvc2017_64 폴더를 Add 한다.

 

설치가 완료 되었으면 Qt Creator를 실행하고 Qt Widgets Application 프로젝트를 만들어 준다.

 

프로젝트 폴더 선택 외에는 기본값으로 진행 한다.

 

설정이 완료되면 아래와 같은 화면이 나온다.

 

 

Forms - Mainwindow.ui 디자인 화면에서 PushButton과 Label을 적당한 위치에 배치한다. Label은 기본 크기보다 약간 크게 늘려 준다.

Label의 Property에서 alignment - Horizontal을 AlignHCenter로 바꿔준다.

 

PushButton에서 오른쪽 클릭 - Go to slot... 을 선택한다.

 

QAbstractButton - clicked() 를 선택한다.

 

mainWindow.cpp 에 on_pushButton_clicked() 가 생성된다.

 

 

mainwindow.h 에 QMessageBox 헤더 파일을 include 하고 IsClicked, OriginalStatus, MsgBox 멤버 변수를 추가한다.

 

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
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include <QMessageBox>
 
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
 
private slots:
    void on_pushButton_clicked();
 
private:
    Ui::MainWindow *ui;
 
    bool IsClicked;
    QString OriginalStatus;
    QMessageBox MsgBox;
};
 
#endif // MAINWINDOW_H
cs

 

mainwindow.cpp 에서 constructor와 on_pushButton_clicked() 를 아래와 같이 수정해 준다.

 

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
#include "mainwindow.h"
#include "ui_mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
 
    IsClicked = false;
    OriginalStatus = ui->pushButton->styleSheet();
    ui->label->setText("Unchanged");
    MsgBox.setWindowTitle("Sean");
    MsgBox.setText("Button Color Change");
    MsgBox.setInformativeText("Do you want to change button color?");
    MsgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
    MsgBox.setDefaultButton(QMessageBox::Yes);
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::on_pushButton_clicked()
{
    if (IsClicked == false)
    {
        int ret = MsgBox.exec();
 
        switch(ret)
        {
            case QMessageBox::Yes:
                ui->pushButton->setStyleSheet("color: blue;"
                                              "background-color: red;");
                ui->label->setText("Changed");
                IsClicked = !IsClicked;
                break;
 
            case QMessageBox::No:
                ui->label->setText("No");
                break;
 
            default:
                ui->label->setText("Cancel");
                break;
        }
    } else {
        IsClicked = !IsClicked;
        ui->pushButton->setStyleSheet(OriginalStatus);
        ui->label->setText("Unchanged");
    }
}
cs

 

 

빌드(Ctrl + B) 후 실행 (Ctrl + R) 한다.

 

PushButton을 클릭하면 MessageBox가 나온다.

 

Yes를 클릭하면 PushButton의 색과 Label 의 text가 변한다.

 

 

반응형
Posted by J-sean
:
반응형

JSON (JavaScript Object Notation)은 가벼운 data 교환 포멧이다. C++이 공식으로 지원하는 형식은 아니지만 분석에 사용 가능한 여러가지 라이브러리가 있다. 그 중 JsonCpp의 사용 방법이다.


홈페이지에서 소스를 다운 받고 압축을 풀면 아래와 같은 파일들이 나온다.


amalgamate.py를 실행한다.


dist라는 폴더에 소스파일과 헤더 파일이 생성된다.


makefiles - mscv2010 - jsoncpp.sln을 실행 한다.


Retarget Projects가 실행된다.


3개의 프로젝트가 나타난다.


각 프로젝트의 Property Pages - Configuration Properties - C/C++ - Code Generation - Runtime Library를 /MDd로 바꿔 준다.


Build 해 준다.


makefiles - msvc2010 - Debug 폴더에 lib_json.lib가 생성된다.


JsonCpp를 사용할 프로젝트를 만들고 Include Directory(jsoncpp-master\include)와 Library Directory(jsoncpp-master\makefiles\msvc2010\Debug)를 추가해 준다.




쓰기 예제

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
#pragma comment (lib, "lib_json.lib")
 
#include <iostream>
#include <fstream>
#include "json/json.h"
 
using namespace std;
using namespace Json;
 
int main()
{
    ofstream json_file;
    json_file.open("JSON_DATA.json");
 
    Value Computer;
    Computer["CPU"= "I7";
    Computer["RAM"= "16G";
 
    Value Language;
    Language["C++"= "Visual Studio";
    Language["Python"= "IDLE";
    
    Computer["Program"= Language;
    Computer["HDD"= "2TB";
 
    Value Cable;
    Cable.append("Power");
    Cable.append("Printer");
    Cable.append("Mouse");
 
    Computer["Computer"]["Cable"= Cable;
 
    Value number;
    number["Int"= 123;
    number["Double"= 456.012;
    number["Bool"= true;
 
    Computer["Computer"]["Number"= number;
 
    StreamWriterBuilder builder;
    builder["commentStyle"= "None";
    builder["indentation"= "    ";  // Tab
    unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
 
    // 알파벳 순으로 write 된다.
    writer->write(Computer, &cout);
    writer->write(Computer, &json_file);
    cout << endl;  // add lf and flush
 
    json_file.close();
 
    return 0;
}
cs


아래와 같은 결과가 출력 된다.


같은 결과의 JSON_DATA.json 파일이 생성 된다.

읽기 예제

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
#pragma comment (lib, "lib_json.lib")
 
#include <iostream>
#include <fstream>
#include "json/json.h"
 
using namespace std;
using namespace Json;
 
int main()
{
    ifstream json_dir("JSON_DATA.json");
    CharReaderBuilder builder;
    builder["collectComments"= false;
    Value value;
 
    JSONCPP_STRING errs;
    bool ok = parseFromStream(builder, json_dir, &value, &errs);
 
    if (ok == true)
    {
        cout << "CPU: " << value["CPU"<< endl;
        cout << "Program Python: " << value["Program"]["Python"<< endl;
        cout << "Computer Cable: " << value["Computer"]["Cable"<< endl;
        cout << "Computer Cable[0]: " << value["Computer"]["Cable"][0<< endl;
        cout << endl;
 
        cout << "Computer Number Int(as int): " << value["Computer"]["Number"].get("Int"-1).asInt() << endl;
        // "Int" 값이 없으면 -1 반환.
        cout << "Computer Number Int(as int): " << value["Computer"]["Number"]["Int"].asInt() << endl;
        // "Int" 값이 없으면 0 반환.
        cout << "Computer Number Double(as double): " << value["Computer"]["Number"].get("Double"-1).asDouble() << endl;
        // "Double" 값이 없으면 -1 반환.
        cout << "Computer Number Double(as string): " << value["Computer"]["Number"].get("Double""Empty").asString() << endl;
        // "Double" 값이 없으면 Empty 반환.
        cout << "Computer Number Bool(as bool): " << value["Computer"]["Number"].get("Bool"false).asBool() << endl;
        // "Bool" 값이 없으면 false 반환.
        cout << endl;
 
        cout << "Root size: " << value.size() << endl;
        cout << "Program size: " << value["Program"].size() << endl;
        cout << "Computer Cable size: " << value["Computer"]["Cable"].size() << endl;
        cout << endl;
 
        int size = value["Computer"]["Cable"].size();
        // size() 값을 for 문에서 그대로 비교하면 warning C4018가 발생 한다.
        for (int i = 0; i < size; i++)
            cout << "Computer Cable: " << value["Computer"]["Cable"][i] << endl;
        cout << endl;
 
        for (auto i : value["Computer"]["Cable"])
            cout << "Computer Cable: " << i << endl;
    }
    else
    {
        cout << "Parse failed." << endl;
    }
 
    return 0;
}
cs


아래와 같은 결과가 출력 된다.



반응형

'C, C++' 카테고리의 다른 글

Qt 스프라이트 애니매이션  (0) 2019.02.21
Qt 설치 및 간단한 사용 예  (4) 2019.01.16
Console 어플리케이션에 이미지 디스플레이 하기  (0) 2018.11.22
Python C API  (0) 2018.11.21
MySQL C API  (0) 2018.11.20
Posted by J-sean
:
반응형

Console에 이미지를 디스플레이 하는 간단한 코드.

윈도우 어플리케이션처럼 이미지가 지워졌을때 다시 그려주는 코드가 없기 때문에 커서 이동, 마우스 클릭등으로 이미지가 지워져도 다시 그려주지는 않는다.


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
#include<stdio.h>
#include<Windows.h>
 
int main(void)
{
    printf("Image loading...\n");
    Sleep(100); // 콘솔이 나타날때까지 잠시 멈추지 않으면 이미지가 표시되지 않는 경우가 생긴다.
 
    HWND hWnd = GetConsoleWindow();
    // Retrieves the window handle used by the console associated with the calling process.
 
    HBITMAP hImage, hOldBitmap;
 
    HDC hDC = GetDC(hWnd);
    HDC hMemDC = CreateCompatibleDC(hDC);
 
    hImage = (HBITMAP)LoadImage(NULL, TEXT("cat.bmp"), IMAGE_BITMAP, 00, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
    // Loads an icon, cursor, animated cursor, or bitmap.
 
    hOldBitmap = (HBITMAP)SelectObject(hMemDC, hImage);
    BitBlt(hDC, 505050 + 61250 + 409, hMemDC, 00, SRCCOPY); // Image(612, 409) at (50, 50)
    // The BitBlt function performs a bit-block transfer of the color data corresponding to a rectangle of pixels
    // from the specified source device context into a destination device context.
 
    SelectObject(hMemDC, hOldBitmap);
    DeleteObject(hImage);
    DeleteDC(hMemDC);
    ReleaseDC(hWnd, hDC);
 
    return 0;
}
cs


결과:






반응형

'C, C++' 카테고리의 다른 글

Qt 스프라이트 애니매이션  (0) 2019.02.21
Qt 설치 및 간단한 사용 예  (4) 2019.01.16
How to install and use JsonCpp - JsonCpp 설치 및 사용  (2) 2019.01.08
Python C API  (0) 2018.11.21
MySQL C API  (0) 2018.11.20
Posted by J-sean
: