triumphost 120 Posting Whiz

The pixel you are trying to get is outside the window's clipping region.. 500, 500 is probably larger than your Window..

GetPixel Documentation

See what it says for the return value..

triumphost 120 Posting Whiz

Show some better effort rather than copy pasting.. I really shouldn't be giving you code for apparently no reason but I feel nicer for some reason..

It can be done as follows:

#include <iostream>
#include <sstream>

int tobase10(const char* Value)
{
    int Dec = 0, Bin = strtoul(Value, 0, 10);

    for (int I = 0; Bin > 0; ++I)
    {
        if(Bin % 10 == 1)
        {
            Dec += (1 << I);
        }
        Bin /= 10;
    }

    return Dec;
}

int tobase10(int num)
{
    int res = 0;
    std::stringstream ss;
    ss << std::dec << num;
    ss >> res;
    return res;
}

int main()
{
    std::cout<<tobase10("11111111")<<"\n"; //binary to dec.
    std::cout<<tobase10(0377)<<"\n";       //octal to dec.
    std::cout<<tobase10(0xFF)<<"\n";       //hex to dec.
    return 0;
}
triumphost 120 Posting Whiz
#include <iostream>

void printrowmajor(int* arr, int width, int height)
{
    for (int i = 0; i < height; ++i)
    {
        for (int j = 0; j < width; ++j)
            std::cout<<arr[i * width + j]<<" ";

        std::cout<<"\n";
    }
}

void printcolumnmajor(int* arr, int width, int height)
{
    for (int i = 0; i < width; ++i)
    {
        for (int j = 0; j < height; ++j)
            std::cout<<arr[i + j * width]<<" ";

        std::cout<<"\n";
    }
}

int main()
{
    int arr[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

    printrowmajor(&arr[0], 4, 3);

    std::cout<<"\n";

    printcolumnmajor(&arr[0], 4, 3);
    return 0;
}

This will print:

0 1 2 3 
4 5 6 7 
8 9 10 11 

0 4 8 
1 5 9 
2 6 10 
3 7 11 

This.. will also print the same thing:

int main()
{
    int arr[3][4] =
    {
        {0, 1, 2, 3},
        {4, 5, 6, 7},
        {8, 9, 10, 11}
    };

    printrowmajor(&arr[0][0], 4, 3);

    std::cout<<"\n";

    printcolumnmajor(&arr[0][0], 4, 3);
    return 0;
}
triumphost 120 Posting Whiz
triumphost 120 Posting Whiz

That is not what your teacher wants you to do. They do not want you to create pointers to already created arrays.. Btw, avoid creating an array of size 0.

Your teacher wants:

  1. You to read the first line of the file into an integer "ItemCount".
    This integer will hold the amount of lines/items to read.

  2. You must then create arrays of "ItemCount" in size.
    So if the first line of the file is 3, you must create an array of size 3.
    If the first line of the file is 4, you must create arrays of size 4.

This can be done like so:

void ReadFile(int &ItemCount, int* &ItemNumbers, double* &Prices, int* &Quantities)
{
    std::fstream File("inventoryData.txt", std::ios::in); //Setup the stream to read the file.

    if (File.is_open()) //If we can open the file, lets start reading it.
    {
        File >> LinesRead;  //Read the first line of the file. Store it in "ItemCount" variable.

        ItemNumbers = new int[ItemCount]; //Allocate space to hold "3" integers aka "ItemCount" amount.
        Prices = new double[ItemCount]; //Same thing.. we need space for 3 prices.
        Quantities = new int[ItemCount]; //And 3 quantities..

        for (int i = 0; i < ItemCount; ++i)  //Lets read "3" lines/items.. Remember "ItemCount" is the first line of the file. Aka "3".
        {
            File >> ItemNumbers[i]; //Read item number first. Just like std::cin >> ItemNumbers[i];
            File >> Prices[i];      //Read prices next.
            File >> Quantities[i];  //Read quantities after.
        }

        File.close(); //Close it when finished.
    }
}

int main()
{ …
triumphost 120 Posting Whiz

Basically, instead of having a stack allocated array of some size, you need to allocate the array on the heap. Allocating via new[] will give you a pointer to the data. However, there is one downside.. You must now delete[] the array after you're done using it!

For example:

#include <fstream>
#include <iostream>

void ReadFile(int* LinesRead, int** ItemNumbers, double** Prices, int** Quantities)
{
    std::fstream File("inventoryData.txt", std::ios::in);
    if (File.is_open())
    {
        File >> *LinesRead; //Store the amount of lines read into the variable.
        *ItemNumbers = new int[*LinesRead]; //Allocate "LinesRead" integers.
        *Prices = new double[*LinesRead];   //Allocate "LinesRead" doubles.
        *Quantities = new int[*LinesRead];  Allocate "LinesRead" integers.

        for (int i = 0; i < *LinesRead; ++i)
        {
            File >> (*ItemNumbers)[i] >> (*Prices)[i] >> (*Quantities)[i];
        }

        File.close();
    }
}


int main()
{
    int LinesRead = 0;
    int* ItemNumbers = NULL; //Pointer to integers
    double* Prices = NULL;   //Pointer to doubles
    int* Quantities = NULL;  //Pointer to integers

    ReadFile(&LinesRead, &ItemNumbers, &Prices, &Quantities); //Pass the address of each pointer.

    for (int i = 0; i < LinesRead; ++i)
        std::cout<<"Item#: "<<ItemNumbers[i]<<" Price: "<<Prices[i]<<" Quantity: "<<Quantities[i]<<"\n";

    delete[] ItemNumbers;
    delete[] Prices;
    delete[] Quantities;
}

That is the same as the below (which uses references instead):

#include <fstream>
#include <iostream>

void ReadFile(int &LinesRead, int* &ItemNumbers, double* &Prices, int* &Quantities)
{
    std::fstream File("inventoryData.txt", std::ios::in);
    if (File.is_open())
    {
        File >> LinesRead;
        ItemNumbers = new int[LinesRead];
        Prices = new double[LinesRead];
        Quantities = new int[LinesRead];

        for (int i = 0; i < LinesRead; ++i)
        {
            File >> ItemNumbers[i] >> Prices[i] >> Quantities[i];
        } …
triumphost 120 Posting Whiz

It is by far easier to work with Bitmaps. I'm not used to GDI+ however, does your socket send all the bytes?

If you use Bitmaps, then the following can work for you:

HBITMAP PixelsToHBitmap(void* Pixels, int Width, int Height, unsigned short BitsPerPixel)
{
    void* Memory = nullptr;
    HBITMAP ImageHandle = nullptr;
    BITMAPINFO Info = {{sizeof(BITMAPINFOHEADER), Width, -Height, 1, BitsPerPixel, BI_RGB, 0, 0, 0, 0, 0}};
    ImageHandle = CreateDIBSection(nullptr, &Info, DIB_RGB_COLORS, &Memory, nullptr, 0);
    memcpy(Memory, Pixels, Width * Height * 4);
    return ImageHandle;  //DO NOT FORGET TO DeleteObject later!
}

If you still wish to use JPEG, I'm sure it won't be too hard to look up how to get an hBitmap from Pixels for it..

triumphost 120 Posting Whiz

lol Ancient, the unicode is actually an instance of the class you see above.

BufferedStream<std::ostream> unicout(std::cout);
triumphost 120 Posting Whiz

I've created:

#include <streambuf>
#include <iostream>
#include <windows.h>


template<typename T>
class BufferedStream : T
{
    private:
        T &stream;
        std::streambuf* buffer; //planning to use this to create other "IO" functions.

    public:
        BufferedStream(T &stream) : stream(stream), buffer(stream.rdbuf()) {}
        ~BufferedStream() {stream.rdbuf(this->buffer);};

        std::ostream& operator << (const char* data);
        std::ostream& operator << (const std::string &data);
        std::wostream& operator << (const wchar_t* data);
        std::wostream& operator << (const std::wstring &data);
};

template<typename T>
std::ostream& BufferedStream<T>::operator << (const char* data)
{
    SetConsoleOutputCP(CP_UTF8);
    DWORD slen = lstrlenA(data);
    WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), data, slen, &slen, nullptr);
    return *this;
}

template<typename T>
std::ostream& BufferedStream<T>::operator << (const std::string &data)
{
    SetConsoleOutputCP(CP_UTF8);
    DWORD slen = data.size();
    WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), data.c_str(), data.size(), &slen, nullptr);
    return *this;
}

template<typename T>
std::wostream& BufferedStream<T>::operator << (const wchar_t* data)
{
    DWORD slen = lstrlenW(data);
    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), data, slen, &slen, nullptr);
    return *this;
}

template<typename T>
std::wostream& BufferedStream<T>::operator << (const std::wstring &data)
{
    DWORD slen = data.size();
    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), data.c_str(), slen, &slen, nullptr);
    return *this;
}

BufferedStream<std::ostream> unicout(std::cout);
BufferedStream<std::istream> unicin(std::cin);

int main()
{
    const char s[] = "Русский текст в консоли\n";
    unicout<<s;
}

because of this problem I'm having: http://stackoverflow.com/questions/21370710/unicode-problems-in-c-but-not-c

Anyway, the problem states that I can use unicode in C but not in C++. I have no clue why as I did everything right. I however found that the above class which I wrote to combat this problem works just fine. I want to know if there is a better way to do this at all?

Any ideas?

triumphost 120 Posting Whiz

@mike_2000_17 http://stackoverflow.com/questions/4195691/to-use-shared-ptr-is-it-safe and http://stackoverflow.com/questions/3899790/shared-ptr-magic
and even http://stackoverflow.com/questions/3899688/default-virtual-dtor/3899726#3899726

Apparently shared_ptr is implemented in such a way that the virtual destructor isn't needed.. It is apparently the only container implemented in such a way.

Live Test case: http://ideone.com/D2Lqoa

I was pretty shocked that was even possible.. Does not work for anything other than a shared_ptr. @OP, I am fairly certain you would be leaking if it wasn't for the accidental choice of using shared_ptr.

I guess that might make it safer to derive from stl containers such as std::string

It's actually the first time I ever heard of that or even saw something like that.

triumphost 120 Posting Whiz

Not sure if it's just me or not but I think the first example might be leaking? No virtual destructor so when std::shared_ptr calls delete on the IFoo, doesn't the destructor of the actual object NOT get called?

I'm actually not sure how I'd debug it to tell..

triumphost 120 Posting Whiz

I have the following code for 2D dimensional arrays being flattened as 1D C-style arrays:

#include <iostream>

int main()
{
    int width = 4, height = 10;

    int arr[width * height];

    for (int i = 0, k = 0; i < height; ++i)
    {
        for (int j = 0; j < width; ++j)
        {
            arr[i * width + j] = k++;
        }
    }



    for (int i = 0; i < height; ++i)
    {
        for (int j = 0; j < width; ++j)
        {
            int* ptr = &arr[0] + height * i; //perfect also works with &arr[0] + width * i;
            std::cout<<ptr[j]<<"   ";
        }
    }
}

It prints: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
as demonstrated here: http://ideone.com/gcgocu
The array does NOT have to be a square (4x4) and the above still works.

Knowing that the above works, I made a class out of it and I defined an index operator as:

int* operator [](const int index) {return ptr + width * index;}

Such that I can do: Instance[i][j] and it works just fine.

Now I'm trying to do the same thing with a 3D array so I did:

#include <iostream>

int main()
{
    int width = 4, height = 4, depth = 4;

    int arr[width * height * depth];

    for (int i = 0, l = 0; i < depth; ++i)
    {
        for (int j = 0; j < height; ++j) …
triumphost 120 Posting Whiz
#include <windows.h>
#include <stdio.h>

#define GetPixel(Bmp, X, Y) (((Bmp)->Pixels[(Y) * (Bmp)->Width + (X)]) & 0x00FFFFFF)
#define PixelToColour(Pixel) (COLORREF)(((Pixel) & 0xFF00FF00) | (((Pixel) & 0xFF0000) >> 16) | (((Pixel) & 0xFF) << 16))

typedef struct
{
    HBITMAP hBmp;
    int Width, Height;
    unsigned int* Pixels;
    unsigned short BitsPerPixel;
} BmpData;

typedef enum {false = 0, true = 1} bool;

bool ScreenShot(BmpData* Data)
{
    bool Result = false;
    memset(Data, 0, sizeof(BmpData));
    HDC hdcScreen = GetDC(NULL);
    HDC hdcMem = CreateCompatibleDC(NULL);
    Data->Width = GetDeviceCaps(hdcScreen, HORZRES);
    Data->Height = GetDeviceCaps(hdcScreen, VERTRES);

    unsigned char* Pixels = NULL;
    unsigned short BitsPerPixel = 32;
    BITMAPINFO Info = {{sizeof(BITMAPINFOHEADER), Data->Width, -Data->Height, 1, BitsPerPixel, BI_RGB, 0, 0, 0, 0, 0}};

    Data->hBmp = CreateDIBSection(hdcScreen, &Info, DIB_RGB_COLORS, (void**)&Pixels, NULL, 0);
    if(Data->hBmp)
    {
        HBITMAP hOld = (HBITMAP)SelectObject(hdcMem, Data->hBmp);
        BitBlt(hdcMem, 0, 0, Data->Width, Data->Height, hdcScreen, 0, 0, SRCCOPY);
        SelectObject(hdcMem, hOld);
        Data->Height *= -1;
        Data->BitsPerPixel = BitsPerPixel;
        Data->Pixels = (unsigned int*)Pixels;
        Result = true;
    }

    DeleteDC(hdcMem);
    DeleteDC(hdcScreen);
    return Result;
}

void SaveBitmap(const char* FilePath, const BmpData* Data)
{
    FILE* hFile = fopen(FilePath, "wb+");
    if (!hFile)
    {
        printf("%s", "Error. Cannot Create Bitmap.");
        return;
    }

    unsigned int Trash = 0;
    unsigned short Planes = 1;
    unsigned int biSize = 40;
    unsigned short Type = 0x4D42;
    unsigned int compression = 0;
    unsigned int PixelsOffsetBits = 54;
    int Width = Data->Width;
    int Height = -Data->Height;
    unsigned short BitsPerPixel = Data->BitsPerPixel;
    unsigned int size = ((Width * BitsPerPixel + 31) / 32) * 4 * Height;
    unsigned int bfSize = 54 + size;
    Height *= -1;

    fwrite(&Type, sizeof(char), sizeof(Type), hFile);
    fwrite(&bfSize, …
triumphost 120 Posting Whiz

Now sure what that colour parameter is, but I use this:

void SetTransparency(HWND hwnd, std::uint8_t Transperancy)
{
    long wAttr = GetWindowLong(hwnd, GWL_EXSTYLE);
    SetWindowLong(hwnd, GWL_EXSTYLE, wAttr | WS_EX_LAYERED);
    SetLayeredWindowAttributes(hwnd, 0, Transperancy, 0x2);
}

SetTransparency(Some_Window_Handle, 0); //100% transparency
SetTransparency(Some_Window_Handle, 128); //50% transparency
SetTransparency(Some_Window_Handle, 255); //0% transparency
ddanbe commented: Nice. +14
triumphost 120 Posting Whiz

Oh ok, I was not aware that I had to publish it with a license. There's no way for me to delete posts though.

As for the deleting of the memory in WindowProcedure. I was aware that it is leaking but I wasn't sure whether I should do something about it. The reason is because I saw the wxWidgets hello world example below:

bool MyApp::OnInit()
{
    MyFrame *frame = new MyFrame( _("Hello World"), wxPoint(50, 50), wxSize(450, 340) );
    frame->Show(true);
    SetTopWindow(frame);
    return true;
}

Notice that myframe is never deleted! None of the controls they create are ever deleted! Every example I ever see uses new and somehow never deletes a single thing.

I asked on StackOverflow and someone said: "The memory is deleted when the application is closed so just leave it".

I know it sounds extremely stupid and makes my eye twitch but I thought to myself, "they have 98k+ rep and are far better than I am, wxWidgets is a public and popular api, so it must be doing something right..".

That's why I didn't delete it. Any idea if what they said is true? Why does wxWidgets not delete? Is there a way to override new so that it when someone does:

new Something() it automatically deletes?

Yeah it has a lot of virtual functions but that is the only way I know how to override a base class function.

You should consider finding a way to get rid of any relics of a C …

triumphost 120 Posting Whiz

If someone can edit my post for me, that would be great. If so, then please delete this comment.

Not sure why it won't let me edit the article but I was going to change:

Control.hpp:

std::map<std::int32_t, std::function<void(HWND, UINT, WPARAM, LPARAM)>> Functions;

Control.cpp:

void Control::SetEvent(std::size_t Index, std::function<void(HWND, UINT, WPARAM, LPARAM)> Func)
{
    if (Func != nullptr)
    {
        this->Functions.insert(std::make_pair(Index, Func));
    }
}

void Control::ProcessEvent(std::size_t Index, HWND Hwnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    if (this->Functions[Index] != nullptr)
    {
        this->Functions[Index](Hwnd, Msg, wParam, lParam);
    }
}

LRESULT __stdcall Control::SubClass(HWND Window, UINT Msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
    //GET DYNAMIC ID.. GetWindowLong(HWnd, GWL_ID);
    //GET CLASS NAME.. GetClassName(HWnd, out LPSTR, MaxCount);
    Control* Instance = reinterpret_cast<Control*>(dwRefData);

    switch(Msg)
    {
        case WM_NCDESTROY:
        {
            RemoveWindowSubclass(Window, GlobalSubClass ? GlobalSubClass : SubClass, uIdSubclass);
            return DefSubclassProc(Window, Msg, wParam, lParam);
        }

        default:
            Instance->ProcessEvent(Msg, Window, Msg, wParam, lParam);
            return DefSubclassProc(Window, Msg, wParam, lParam);
    }
    return 0;
}

Thus the sample example is MUCH shorter and becomes:

#include <windows.h>
#include "BaseForm.hpp"
#include "Form.hpp"
#include "Controls.hpp"

class Window : public Form
{
    public:
        using Form::Form;
        Window(std::string Title, std::string Class, WNDPROC WindowProcedure, int Width, int Height)
            : Form(Title, Class, WindowProcedure, {0}, 0, WS_OVERLAPPEDWINDOW, {CW_USEDEFAULT, CW_USEDEFAULT}, Width, Height)
        {}

        int Show() override {return ShowWindow(Form::Handle(), SW_SHOW);}
        int MessageLoop() {return Form::MessageLoop();}
        HWND Handle() {return Form::Handle();}
};

enum EVENT
{
    MOUSE_MOVE, MOUSE_WHEEL, MOUSE_LBUTTONDOWN, MOUSE_LBUTTONUP, MOUSE_LBUTTONDBLCLK, MOUSE_ACTIVATE,
    MOUSE_LEAVE, MOUSE_RBUTTONDOWN, MOUSE_RBUTTONUP, MOUSE_RBUTTONDBLCLK,
    KEY_DOWN, KEY_UP
};

MenuBar* Mnb;
TextBox* ReceiveBox;
TextBox* SendBox;
Button* SendButton;
ListBox* ContactsBox;
PictureBox* FriendPicture;
PictureBox* ClientPicture;


LRESULT WindowProcedure(HWND Hwnd, UINT …
triumphost 120 Posting Whiz

Hmm I'm not sure what you mean by SuperClass WindowProc?

Here's how I create all my WINAPI Controls AND Windows: http://www.daniweb.com/software-development/cpp/code/470562/winapi-object-oriented-classes

It allows for Events easily and all of the work is already done.

triumphost 120 Posting Whiz

The sample working code above will create a GUI that looks like:

d031fa04e76273e62b89e2173fd3ccb6

triumphost 120 Posting Whiz

Creating WinAPI windows and controls can be a pain and quite difficult/annoying at times. Most of the time, I find myself searching MSDN, DaniWeb, and StackOverflow. I hate having to use external libraries unless I absolutely have no other choice.

Below contains code for creating WinAPI windows, Controls, Sub-Classing, and EventHandling for each control. There is a sample working code below this article and an image of what the sample code produces.

There are only 4 files to include to your projects:

Form.hpp -- Form.cpp
Controls.hpp -- Controls.cpp

The code for these files are as follows:

Form.hpp:

#ifndef FORM_HPP_INCLUDED
#define FORM_HPP_INCLUDED

#include <windows.h>
#include <iostream>

class Form
{
    public:
        Form(std::string Title, std::string Class, WNDPROC WindowProcedure = nullptr, WNDCLASSEX WndClass = {0}, DWORD dwStyleEx = 0, DWORD dwStyle = WS_OVERLAPPEDWINDOW, POINT Location = {CW_USEDEFAULT, CW_USEDEFAULT}, int Width = CW_USEDEFAULT, int Height = CW_USEDEFAULT, HWND Parent = HWND_DESKTOP, HMENU Menu = nullptr);
        Form(const Form &F) = delete;
        Form(Form && F) = delete;
        virtual ~Form();

    private:
        bool Message = false;
        HWND WindowHandle = nullptr;
        Form& operator = (const Form &F) = delete;
        Form& operator = (Form && F) = delete;
        static LRESULT __stdcall WindowProcedure(HWND Hwnd, UINT Msg, WPARAM wParam, LPARAM lParam);

    protected:
        MSG Messages = {nullptr};
        virtual int Show() = 0;
        virtual int MessageLoop();
        virtual HWND Handle() const {return WindowHandle;}
        virtual void SubClassWindow(HWND Window, WNDPROC SubClassProc);
        virtual void UnSubClassWindow(HWND Window);
};


#endif // FORM_HPP_INCLUDED

Form.cpp:

#include "Form.hpp"

void Form::SubClassWindow(HWND Window, WNDPROC SubClassProc)
{
    SetWindowLongPtr(Window, GWLP_USERDATA, static_cast<LONG_PTR>(SetWindowLongPtr(Window, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(SubClassProc))));
} …
triumphost 120 Posting Whiz

What moschops is saying is that you need to check for an empty vector or end iterator OR make sure that vector v is not empty.

std::vector<int>::iterator it = (max_element(v.begin(), v.end()));
if (it != v.end())
{
    maxValue = *it;
    //all other code (that for loop) goes here..
}
else
{
    std::cout<<"Vector v is empty!!\n";
}
triumphost 120 Posting Whiz

As you can see CPP libs do not come with a time sleep/wait fuction to use
in your code/loop.

In C++11:

std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::this_thread::sleep_for(std::chrono::nanoseconds(1000000));
std::this_thread::sleep_for(std::chrono::seconds(1));
std::this_thread::sleep_until(.....);

and so on..

Ancient Dragon commented: Excellent :) +14
triumphost 120 Posting Whiz

Is this a console program or a GUI program? Windows or Linux?

For Windows, it is all UTF-16. Thus you'll need to convert from UTF-8 to UTF-16 unless you are already using UTF-16.

If it is WINAPI, you'll need to use only the Unicode functions such as: DrawTextW, SetWindowTextW, TextOutW, etc.. These use UTF-16.

If it is a console program, then you need to decide a format; UTF-8 or UTF-16. You'll then need to do conversions manually or use a library to handle them for you.

You can write to the console using std::wcout or WriteConsoleW.

triumphost 120 Posting Whiz

@OP, all you need to look at is the WM_CTLCOLORSTATIC case. The other cases are just there to show the different messages that need to be handled when painting. I wish I could tell you it is as easy as handling WM_PAINT but I'd be lying to you then.

WM_CTRLCOLORSTATIC is used for painting static controls (such as labels) or read-only controls (such as read-only edit/textbox controls): http://msdn.microsoft.com/en-us/library/windows/desktop/bb787524(v=vs.85).aspx

wParam will have the HDC to the control that is being painted. You can use wParam in any paint functions such as SetTextColor((HDC)wParam, ...)

lParam will have the HWND of the control to be painted and this can be used to see which control the window is drawing or moving or resizing, etc..

An very quick example I whipped up:

HWND MyLabel = NULL;
HWND MyReadOnlyEdit = NULL;

LRESULT WndProc(HWND hwnd, MSG msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_CREATE:
        {
            //Create some label. Aka a static control.
            MyLabel = CreateWindow("STATIC","My Label Text", WS_VISIBLE | WS_CHILD, 10, 200, 75, 35, hWnd, (HMENU)LABEL_ID, hInstance, 0);

            //Create some read-only edit control.
            MyReadOnlyEdit = CreateWindowEx("EDIT", "My Edit Text", WS_CHILD | WS_VISIBLE | ES_READONLY, 0, 0, 100, 100, hwnd, (HMENU)EDIT_ID, hInstance, 0);
        }

        case WM_CTRLCOLORSTATIC:
        {
            HWND somecontrol = (HWND)lParam; //lParam is the control's handle.

            if (somecontrol == MyLabel) //if it is our label control..
            {
                //Paint the label.

                HDC hdc = (HDC)wParam; //wParam is the HDC to our control

                SetTextColor(hdc, RGB(255, 0, 0)); //Set our label's text colour to red. …
triumphost 120 Posting Whiz

@AncientDragon, that event greek looking code is a lambda. It's just a function that will be run when an event occurs.

@OP.. WIN32/WINAPI code others are posting would be correct if they took into consideration that Labels (the control you want to paint) is a static control (no insult to them as they taught me all that I know). Well AFAIK, labels do not send WM_PAINT. Labels send the WM_CTLCOLORSTATIC message and that is why your WM_PAINT is being ignored.

case WM_PAINT:
        {
            hdc = BeginPaint(window, &PS);
            //Paint whatever else here.
            EndPaint(window, &PS);
            break;
        }

        case WM_ERASEBKGND: //Erases the window's background. Usually when a window is resized.
        {
            RECT rect = {0};
            HBRUSH Brush = CreateSolidBrush(0xECE6E1); //paint using a custom brush/colour.
            SelectObject((HDC)wParam, Brush);
            GetClientRect(window, &rect);
            Rectangle((HDC)wParam, rect.left - 1, rect.top - 1, rect.right + 1, rect.bottom + 1);
            DeleteObject(Brush);
            break;
        }

        case WM_CTLCOLORSTATIC:  //For painting static OR read-only/disabled controls backgrounds.
        {
            //a label is a read-only static control. This code will change the label's text color and background colour.
            if (WelcomeLabel == (HWND)lParam)
            {
                hdc = (HDC)wParam;
                SetTextColor(hdc, RGB(0, 0, 0));
                SetBkColor(hdc, 0xECE6E1);
                return (LRESULT)GetStockObject(NULL_BRUSH);
            }
            else if (HelpBox == (HWND)lParam) //edit controls are also static and "can be" read-only.
            {
                hdc = (HDC)wParam;
                SetTextColor(hdc, RGB(0, 0, 0)); //change their text colour.
                SetBkColor(hdc, 0xECE6E1);  //change the background colour.
                return (LRESULT)GetStockObject(NULL_BRUSH);
            }
            break;
        }

There is also:

WM_CTLCOLORBTN 
WM_CTLCOLOREDIT
WM_CTLCOLORLISTBOX
WM_CTLCOLORSCROLLBAR

etc..

cambalinho commented: thanks +2
triumphost 120 Posting Whiz

I was just using the array as a matrix. I don't mind indeterminate values at all if I access an array with no initial value. I just don't want my program crashing or me doing something unsafe because of some undefined behaviour that I don't understand.

I don't know why accessing an uninitialised array would be undefined. I understand indeterminate but not undefined. I don't understand traps by just looking at it either. I'm not sure why I would be able to write to it but not read from it at all. If I can write to it, why can't I read garbage values from it willingly?

I asked someone why it was undefined and they said to me that the OS only gives memory to a variable when it has a value otherwise nothing happens :S

Thank you for your replies.

triumphost 120 Posting Whiz

Why is accessing data in an uninitialised array undefined behaviour?

I ask because I was doing some benchmarking on vector<int> vs. int* vs. int**. My results were: http://stackoverflow.com/questions/20863478/class-using-stdvector-allocation-slower-than-pointer-allocation-by-a-lot

Now I'm being told if I use the raw array and try to access an index without initialising it first, it is undefined behaviour and that I must initialise it. The thing is, if I initialise it, it takes 43 seconds compared to 5 seconds. I'm asking here because I always get better answers here instead of stackoverflow and they are arguing over whether I'm allowed to do it or not.

Any ideas what I could do to keep the speed of uninitialising without breaking any rules?

triumphost 120 Posting Whiz

I'm not exactly sure what you're trying to do here.

However, since you mentioned "mouse stop", I assume you want to know when the mouse has stopped moving. In that case, you're going to need to set a Timer and check the WM_TIMER event. http://msdn.microsoft.com/en-us/library/windows/desktop/ms644906(v=vs.85).aspx
and
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644902(v=vs.85).aspx

What you'll do is.. When you receive a WM_MOUSEMOVE message, call SetTimer with the timerproc paramter as null. If the mouse moves again, you want to call KillTimer. If you receive a WM_TIMER message, it means the mouse has stopped moving.

For example:

LRESULT WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    static UINT_PTR MouseStopTimerID = 1; //Just some unique TimerID.

    switch(msg)
    {
        case WM_MOUSEMOVE:
        {
            KillTimer(hwnd, MouseStopTimerID);
            SetTimer(hwnd, MouseStopTimerID, 500, NULL); //if the mouse hasn't moved for 500ms, a timer event will be triggered.

            //SetTimer(hwnd, MouseStopTimerID, 500, OnMouseStop); //Can be used as a callback as well. Instead of receiving a WM_TIMER, it will call the function "OnMouseStop".
        }
        break;

        case WM_TIMER:
        {
            switch(wParam)
            {
                case MouseStopTimer:
                {
                    /**
                     * Do whatever you want here.. The mouse hasn't moved for 500ms since the timer has been set..
                     */
                    KillTimer(hwnd, MouseStopTimerID); //Kill the timer after processing it.
                }
                return 0; //This procedure must immediately return 0 if it processes a timer event.
            }
        }
        break;

        case WM_DESTROY:
            KillTimer(hwnd, MouseStopTimerID); //Just in case the timer is still alive, kill it before the application closes..
            PostQuitMessage(0);
        break;
    }
}

/*void __stdcall OnMouseStop(HWND hwnd, UINT msg, UINT_PTR TimerID, DWORD …
cambalinho commented: thanks +2
triumphost 120 Posting Whiz

I think the MouseTracking is for client area only. It doesn't make much sense to track the mouse within the window's title bar. Mouse hover is just the amount of time (milliseconds) the mouse has to be in the client area before the WM_MOUSEHOVER event is triggered. In the above code, dwHoverTime is set to one.. If the mouse has been within a window or control's bounds for 1ms or more, the window/control will receive the WM_MOUSEHOVER event. If you set this paramter to 100000, it will need to be within the window's bounds for 100000ms before the window receives the event.

In other words, it does not matter whether the mouse is moving over the window/control, it only matters how long it has been within the window/control's bounds.

triumphost 120 Posting Whiz

You cannot get mouse event like this. You need to "track" the mouse and determine when it has entered and when it has left your window/control. I've written a small example below.

#include <iostream>
#include <windows.h>

void TrackMouse(HWND hwnd)
{
    TRACKMOUSEEVENT tme;
    tme.cbSize = sizeof(TRACKMOUSEEVENT);
    tme.dwFlags = TME_HOVER | TME_LEAVE; //Type of events to track & trigger.
    tme.dwHoverTime = 1; //How long the mouse has to be in the window to trigger a hover event.
    tme.hwndTrack = hwnd;
    TrackMouseEvent(&tme);
}

LRESULT WndProc(HWND Hwnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    static bool Tracking = false;

    switch(Msg)
    {
        case WM_MOUSEMOVE:
        {
            if (!Tracking)
            {
                TrackMouse(Hwnd);
                Tracking = true;
            }
        }
        break;

        case WM_MOUSEHOVER:
            std::cout<<"MOUSE ENTERED\n";
            break;

        case WM_MOUSELEAVE:
            std::cout<<"MOUSE LEFT\n";
            Tracking = false;
            break;

        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;

        default:
            return DefWindowProc(Hwnd, Msg, wParam, lParam);
    }
    return 0;
};
triumphost 120 Posting Whiz

Your operator () is wrong and you also need to tell it what parameters the class takes..

#include <functional>
#include <vector>
#include <iostream>

template<typename... Args>
class events
{
public:
    typedef std::function<void(Args... args)> OnSomethingHandler;

    events(OnSomethingHandler Handler)
    {
        handlers_.push_back(Handler);
    }


    void operator ()(Args... args)
    {
        for(auto i = handlers_.begin(); i != handlers_.end(); ++i)
            (*i)(args...);
    }

private:
    std::vector<OnSomethingHandler> handlers_;

    void AddHandler(OnSomethingHandler Handler)
    {
        handlers_.push_back(Handler);
    }

    void TriggerEvents()
    {
        for(auto i = handlers_.begin(); i != handlers_.end(); ++i)
            (*i)();
    }

};

int main()
{
    events<int, int> foo([](int a, int b){
        std::cout << (a + b) << "\n";
    });

    foo(5, 5);
}
triumphost 120 Posting Whiz

It's not exactly "facial" recognition but if you like rolling your own, I wrote a sort of Image recognition class you can take a look at: https://github.com/Brandon-T/PurelyCPP/blob/master/src/ImageFinder.cpp

and I load my images using: https://github.com/Brandon-T/PurelyCPP/blob/master/src/Images.cpp

It can find images such as Bitmap, PNG, TGA, etc.. You can specify the matching threshold/tolerance for colours and images.

I plan to re-write it one day (and document the code) but you can take a look as see how it is done. It is not "amazing" but it is fairly good and gets the job done.

Otherwise as suggested, you can use OpenCV.

triumphost 120 Posting Whiz

Use ShowWindow in combination with SW_HIDE on the current window - it will hide the console

Just change main to "WinMain" and compile with -mwindows. That way the console never even shows.

triumphost 120 Posting Whiz

Close to that yeah. I came up with:

std::uint32_t CheckSum(const void* Data, std::uint32_t &MeanColour, std::uint32_t &ClippedID, std::size_t Width, std::size_t Height)
{
    std::uint32_t CheckSum = 0;
    int R = 0, G = 0, B = 0, K = 0;
    const std::uint8_t* BuffPos = static_cast<const std::uint8_t*>(Data);

    for (std::size_t I = Height < 12 ? 1 : 12; I < Height; ++I)
    {
        for (std::size_t J = 0; J < Width; ++J)
        {
            int b = *(BuffPos++);
            int g = *(BuffPos++);
            int r = *(BuffPos++);
            CheckSum += *(BuffPos++);

            if (r != 0 && g != 0 && b != 0)
            {
                R += r;
                G += g;
                B += b;
                ++K;
            }
        }
    }

    ClippedID = (K != 0 ? RGB(R / K, G / K, B / K) : RGB(R, G, B));
    BuffPos = static_cast<const std::uint8_t*>(Data);
    R = G = B = K = 0;

    for (std::size_t I = 0; I < Height; ++I)
    {
        for (std::size_t J = 0; J < Width; ++J, ++K)
        {
            R += *(BuffPos++);
            G += *(BuffPos++);
            B += *(BuffPos++);
            ++BuffPos;
        }
    }

    MeanColour = (K != 0 ? RGB(R / K, G / K, B / K) : RGB(R, G, B));
    return CheckSum;
}

Where:
Checksum is the count of alpha pixels starting at height 12.
ClippedID is the average of all RGB pixels starting at height 12.
MeanColour is the average of all RGB pixels starting at height 0.

What I really was trying to do was use 2 for-loops …

triumphost 120 Posting Whiz

In the two for loops below, I want the checksum variable to hold the same value for both even though one loop starts at row 12 and another at row 0.

Any ideas how I can combine these loops so that I don't have to iterate the same buffer twice?

std::uint32_t Checksum = 0;
std::uint32_t CheckSum2 = 0;
std::uint8_t* Ptr = Pixels;

int K = Width < 12 ? 1 : 12;

for (int I = K; I < Height; ++I) //Start at row K offset.
{
    for (int J = 0; J < Width; ++J)
    {
        R += *(Ptr++);
        G += *(Ptr++);
        B += *(Ptr++);

        CheckSum += *(Ptr++);
    }
}



Ptr = Pixels;

for (int I = 0; I < Height; ++I) //Start at 0 offset
{
    for (int J = 0; J < Width; ++J)
    {
        CR += *(Ptr++);
        CG += *(Ptr++);
        CB += *(Ptr++);

        if (I >= K) //if we are at row K?
            CheckSum2 += *(Ptr++);
    }
}

However, CheckSum != Checksum2 so I'm not sure how I can combine them :S

triumphost 120 Posting Whiz

Should I be using std::wstring or std::string and wchar_t or char?

All this unicode stuff is confusing me. I want my application to work on both windows and linux without too many problems and changes but I'm considering unicode vs. ansi.

Any ideas? I ask because I see many applications still using std::string and chars insead of the unicode equivalents.

triumphost 120 Posting Whiz

Aww.. I was so excited when I saw every feature checked off and that it even had some C++14/C++ly features.. I have boost. I just wanted some standard support without external libraries and such and I came across clang. Ah I'll just stick to gcc then.

triumphost 120 Posting Whiz

I want to use it because it says it supports all the C++11 features and I'm hoping that includes Regex as well since gcc isn't near finishing anytime soon..

However, many other websites are saying that clang requires Mingw/gcc to be used in the first place. It doesn't make any sense to me that a compiler requires another compiler and the other compiler's headers to be used. And that I have to build it using gcc as well :S

The clang website also says I need to specify the path to my gcc/mingw headers. :l

So my question is: Does anyone here use Clang on Windows to compile C++? If so, does it have to use the gcc/mingw headers and compiler? I installed CodeLite IDE for clang because I'm not sure that it'll work with codeblocks but I haven't installed clang yet because of this hesitation. I'm not sure I want to use a compiler that depends on another compiler. Anyone?

triumphost 120 Posting Whiz

They are implicitly convertible to T&, so that they can be used as arguments with the functions that take the underlying type by reference.

Source: http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper

triumphost 120 Posting Whiz

I don't know if it's too late to reply since this thread is solved but I wrote something a while ago for a game and the image recognition is pretty flawless and fast too. Way faster than GetPixel. It was previously crossplatform but I thought that I might need bitmaps from a HWND or DC so now it's practically windows only :(
Other than that, it works like this. You create a new instance of "Client". You call Client.SetTarget(....); <-- Accepts a buffer, DC, Hwnd, etc..
That sets the target that will be searched. Whenever you call Client.Find... <-- FindBitmap, FindBitmapTolerance, FindColour, FindColours, etc.. It will search the target for whatever you're looking for. It automatically updates the internal target so you don't have to worry about calling SetTarget every time. Just use the finder functions as you like. So far it supports almost all colour formats. XYZ, RGBA, CIE, CIELAB, etc. 24 and 32 bit bmp's. The CTS Algorithms I got from: https://github.com/MerlijnWajer/Simba/blob/master/Units/MMLCore/bitmaps.pas written in pascal. Mine is different though but it all works the same. The code has tolerances so even if the colour change, it still finds it. Even if the image is partially skewed/deformed, it still finds it.

The idea is from a program called Simba which is created by MerlinWajer and is used for a game called Runescape and many others. It's one of the BEST screenscrapers (website is villavu.com). It is open source as well and they have a huge …

triumphost 120 Posting Whiz
if(!SetWindowLong(hExternalWindow,GWL_STYLE, WS_CHILD | WS_VISIBLE)){MessageBox(nullptr, L"SetWindowLong fail", L"Error", MB_OK);};

Can't.. The window cannot be a child window if it has no parent. Try setting the parent first.

I tried this and it works fine:

case WM_CREATE:
{
    HWND Window = FindWindow("Notepad", "Untitled - Notepad");
    if (Window != nullptr)
    {
        SetParent(Window, hwnd);
        SetWindowPos(Window, nullptr, 0, 0, 0, 0, SWP_NOSIZE);
        RedrawWindow(Window, nullptr, nullptr, RDW_INVALIDATE);
        ShowWindow(Window, SW_SHOW);
    }
}
break;

I don't think WM_CREATE is the right place for it but it works. Just click inside the window and you'll see it shows.

triumphost 120 Posting Whiz
Qstring str = textEdit->toPlainText();
for (auto &s : str)
{
    s.toUpper();
}
textEdit->setPlainText(str);
triumphost 120 Posting Whiz

I use the following and link to "Shell32" and "Ole32":

    #include <windows.h>
    #include <shobjidl.h>

    const GUID CLSID_TaskbarList = {0x56FDF344, 0xFD6D, 0x11D0, {0x95, 0x8A, 0x00, 0x60, 0x97, 0xC9, 0xA0, 0x90}};
    const GUID IID_ITaskbarList = {0x56FDF342, 0xFD6D, 0x11D0, {0x95, 0x8A, 0x00, 0x60, 0x97, 0xC9, 0xA0, 0x90}};
    const GUID IID_ITaskbarList2 = {0x602D4995, 0xB13A, 0x429b, {0xA6, 0x6E, 0x19, 0x35, 0xE4, 0x4F, 0x43, 0x17}};
    const GUID IID_ITaskList3 = {0xEA1AFB91, 0x9E28, 0x4B86, {0x90, 0xE9, 0x9E, 0x9F, 0x8A, 0x5E, 0xEF, 0xAF}};


    void ShowTaskbarIcon(HWND WindowHandle)
    {
        ITaskbarList* TaskListPtr;
        CoInitialize(nullptr);
        long Result = !CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_SERVER, IID_ITaskbarList, reinterpret_cast<void**>(&TaskListPtr));
        if (Result) TaskListPtr->AddTab(WindowHandle);
        TaskListPtr->Release();
        CoUninitialize();
    }

    void HideTaskbarIcon(HWND WindowHandle)
    {
        ITaskbarList* TaskListPtr;
        CoInitialize(nullptr);
        long Result = !CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_SERVER, IID_ITaskbarList, reinterpret_cast<void**>(&TaskListPtr));
        if (Result) TaskListPtr->DeleteTab(WindowHandle);
        TaskListPtr->Release();
        CoUninitialize();
    }
triumphost 120 Posting Whiz

@iamthwee
I can tell that its homework but I wasn't sure since he said "2 week project" or something; I wasn't sure if its a personal one or not.. I did assume it was homework however. What I can't tell from his post is what he is allowed to use and what he's not allowed to do.

I was just asking and not throwing templates at him. I was just giving him an idea.. Its not the template that he should really be looking at but the logic within it.. The template was just there to make his life easier IF he was allowed to use it. I can't just assume that he's not allowed since he never really stated his limitations or what he wants done. All he said was "what would be the best way, must use the dynamic memory array and I am sort of stumped as to what to do next."

And what I mentioned allows him to use "dynamic memory".. Yeah you are right though. He probably isn't ready for it but again, its just a bunch of examples crammed into a class.. I was hoping he'd figure out how it works and sorta use that as an example of where to get started..

.
.
.
.

@OP.. You are still using the wrong delete... If you use new[Size] you need to use delete[].. not delete.

Example:

string* p = new string[Size];

//the above MUST be deleted using delete[]; …
triumphost 120 Posting Whiz

Can you use classes? Have you learned them yet? It'd be a ton easier to manage your array through one.

Also there's quite a bit of errors in your code.. You're using the wrong delete :l

If you do: new[Size] then you need to do delete[].. If you use new then you use delete. Notice the square brackets.

You can always create something like this if you MUST do things manually and are allowed to:

#include <iostream>

using namespace std;


template<typename T>
class DynamicArray
{
    private:
        T* _Data;
        int _Size, _Cap;

    public:
        DynamicArray(int Capacity) : _Data(new T[Capacity]), _Size(0), _Cap(Capacity) {}
        ~DynamicArray() {delete[] _Data; _Data = nullptr; _Size = 0; _Cap = 0;}

        int size() {return _Size;}
        int capacity() {return _Cap;}
        T Get(int Index) {return _Data[Index];}

        void Resize(int NewCapacity);
        void Add(const T &Data);
        void Remove(int Index);
};

template<typename T>
void DynamicArray<T>::Resize(int NewCapacity)
{
    T* Temp = new T[NewCapacity];
    int Max = std::max(_Size, _Cap = NewCapacity);
    std::copy(_Data, _Data + _Size, Temp);
    delete[] _Data;
    _Data = Temp;
}

template<typename T>
void DynamicArray<T>::Add(const T &Data)
{
    if (_Size < _Cap)
    {
        _Data[_Size++] = Data;
    }
    //throw std::runtime_error("Error. Max Capacity Reached. Resize the array.");
}

template<typename T>
void DynamicArray<T>::Remove(int Index)
{
    if (Index < _Size && _Size != 0)
    {
        for (int I = Index; I < _Size - 1; ++I)
        {
            _Data[I] = _Data[I + 1];
        }
        _Data[--_Size] = T();
    }
}

int main()
{
    DynamicArray<std::string> Dim(5);

    Dim.Add("Hello");
    Dim.Add("One");
    Dim.Add("Two");
    Dim.Add("Three");
    Dim.Add("Four");

    Dim.Resize(10);

    Dim.Add("Five");
    Dim.Add("Six");
    Dim.Remove(0);

    for (int I = 0; I < …
triumphost 120 Posting Whiz

Small example.. Uhh you'll have to replace some of the functions with your own but you get the idea.

std::uint32_t RecvEx(SOCKET Socket, void* Buffer, std::uint32_t BufferLength)
{
    char* Pointer = reinterpret_cast<char*>(Buffer);
    std::uint32_t TotalRead = 0;

    while (BufferLength > 0)
    {
        int BytesRead = recv(Socket, Pointer, std::min(1024 * 1024, static_cast<int>(BufferLength)), 0);
        if (BytesRead < 0)
        {
            if ((BytesRead == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
                continue;

            throw std::runtime_error("Error! RecvEx: Failed To Read Bytes.");
        }

        if (BytesRead == 0) break;

        Pointer += BytesRead;
        BufferLength -= BytesRead;
        TotalRead += BytesRead;
    }

    return TotalRead;
}

std::string RecvLine(SOCKET Socket)
{
    char Character = 0;
    std::string Line;

    while(true)
    {
        RecvEx(Socket, &Character, 1);

        if (Character == '\r')
        {
            RecvEx(Socket, &Character, 1);
            if (Character == '\n') break;
            Line += '\r';
        }
        else if (Character == '\n') break;

        Line += Character;
    }
    return Line;
}

void RecvHeaders(SOCKET Socket, std::vector<std::string>* Header)
{
    while(true)
    {
        std::string Line = RecvLine(Socket);
        if (Line.size() == 0) return;
        if (Header) Header->push_back(Line);
    }
}

std::string FindHeader(const std::string &LineToFind, const std::vector<std::string> &Header)
{
    for (std::size_t I = 0; I < Header.size(); ++I)
    {
        int Position = Pos(":", Header[I]);
        if ((Position != -1) && !Header[I].compare(0, Position, LineToFind))
        {
            Position = PosFirstNotOf(" ", Header[I], Position + 1);
            if (Position != -1)
                return Header[I].substr(Position);
        }
    }
    return std::string();
}

std::uint32_t RecvChunkSize(SOCKET Socket)
{
    std::string Line = RecvLine(Socket);
    int Position = Pos(";", Line);
    if (Position != -1) Line.erase(Position);

    char* NextCharacter;
    std::uint32_t Value = strtoul(Line.c_str(), &NextCharacter, 16);

    return (*NextCharacter == '\0') ? Value : -1;
}


void GetPage(std::string WebPage, std::string SavePath)
{ …
triumphost 120 Posting Whiz
template<typename T>
void Transpose(T** Data, std::size_t Size)
{
    for (int I = 0; I < Size; ++I)
    {
        for (int J = 0; J < I; ++J)
        {
            std::swap(Data[I][J], Data[J][I]);
        }
    }
}


int main()
{
    int A[4][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };

    int* Ptr = &A[0][0];
    int** P = &Ptr;

    Transpose(P, 4);   //ERROR! Access Violation.
}

Versus:

int main()
{
    int** B = new int[4];
    for (int I = 0, K = 1; I < 4; ++I)
    {
        B[I] = new int[4];
        for (int J = 0; J < 4; ++J)
        {
            B[I][J] = K++;
        }
    }

    Transpose(B, 4);  //Works fine..
}

So how can I distinquish the difference? In other words, how can I figure out which kind of T** they are passing?

triumphost 120 Posting Whiz

I have roughly 500 function pointers defined in a header like so for example:

void (__stdcall *ptr_glAccum) (GLenum op, GLfloat value);
void (__stdcall *ptr_glActiveTextureARB) (GLenum texture);
void (__stdcall *ptr_glAlphaFunc) (GLenum func, GLclampf ref);
GLboolean (__stdcall *ptr_glAreTexturesResident) (GLsizei n, const GLuint *textures, GLboolean *residences);
void (__stdcall *ptr_glArrayElement) (GLint index);
void (__stdcall *ptr_glBegin) (GLenum mode);
void (__stdcall *ptr_glBindBufferARB) (GLenum target, GLuint buffer);
void (__stdcall *ptr_glBindTexture) (GLenum target, GLuint texture);
void (__stdcall *ptr_glBitmap) (GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
void (__stdcall *ptr_glBlendFunc) (GLenum sfactor, GLenum dfactor);
void (__stdcall *ptr_glBufferDataARB) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);

Now the reason I did not put the typedef or did not want to was because I can assign to and use the pointers above directly. However, if I use the typedef, then I need to create a variable of said type and assign to it then use it. That just increases my code from 1000 lines to 1500+. (500 typedefs, 500 variable declarations, 500 GetProcAddress calls at minimum).

Now when I add a typedef at the beginning of each of those function pointers, my dll is 300kb and compiles in less than 5 seconds.. However, if I remove the typedef as shown above, it skyrockets to 99% cpu when compiling and outputs a 3.51MB dll all while taking 3-4 minutes to compile..

Within the DLL's def file, it shows:

ptr_wglUseFontBitmapsA @940 DATA
ptr_wglUseFontBitmapsW @941 DATA
ptr_wglUseFontOutlinesA @942 DATA
ptr_wglUseFontOutlinesW @943 DATA
triumphost 120 Posting Whiz
std::string From = "From String";

std::wstring To(From.begin(), From.end());

LPCWSTR Last = To.c_str();
triumphost 120 Posting Whiz

I'm trying to write a cout formatter that uses the comma operator and insertion operator. I wasn't able to get that to work so I decided to write it similar to std::boolalpha.

when you use std::boolalpha, it is able to change 0 values to true and false and you can use it like cout << boolalpha.

I was trying to do the same with my "fout" which is supposed to format things printf style by doing:

std::cout<<"Some normal text here"<< fout <<"Test %"<< 1;

and that would print "Some normal text here Test 1".

but that's a bad idea because I wouldn't be able to enter anything else :l

So instead I decided it'd be best if I used the comma operator instead and do:

std::cout<<"Some normal text here" << fout <<"Test %, %", 1, 2<< "works 100% fine."<<std::endl

such that it'd print "Some normal text here Test 1, 2 works 100% fine."

But I'm stuck. I cannot seem to figure out how to get this behaviour at all. I wrote fcout which does this through a function:

template<typename... Args>
void fcout(const char* S, Args... args)
{
    std::size_t I = 0;
    std::vector<tstring> Arguments;
    //Unpack args into Arguments..

    while(*S)
    {
        if (*S == '%')
        {
            if (Arguments.size() <= I)
                throw std::logic_error("Error: Invalid Format. Missing Arguments.");

            cout<<Arguments[I++];
        }
        else
        {
            cout<<*S;
        }
        ++S;
    }
}

BUT its actually bothering me not knowing how to do exactly what I want. Similar to:

#include <iostream>
#include <sstream> …
triumphost 120 Posting Whiz

Using ASM yes.. Iunno what you mean by CPU memory but I assume you mean registers. Just look up some x86 tutorials and download fasm get familiar with some commands then in your compiler, you can do something similar to:

__asm
{
    push ebp
    mov ebp,esp

    mov ecx, 0x6;
    mov eax, SomeData;
    push....
      ;do crap here..
    pop....

    mov esp, ebp
    pop ebx
};