Skip to content

Instantly share code, notes, and snippets.

@sug0
Created November 27, 2018 23:35
Show Gist options
  • Select an option

  • Save sug0/04d36d1615406012ebcac9f45247b21a to your computer and use it in GitHub Desktop.

Select an option

Save sug0/04d36d1615406012ebcac9f45247b21a to your computer and use it in GitHub Desktop.
Windows utility that picks an RGB color, returning it's hex representation
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <windows.h>
// cc -Wall -O2 -o pick.exe pick.c -lcomdlg32
COLORREF fromhexstr(const char *hex)
{
COLORREF color = 0;
int i = 4, it = 0;
const char *p = hex + 1;
if (!*hex || *hex != '#')
return 0;
while (*p && it < 6) {
if (*p >= '0' && *p <= '9') {
color |= (*p - '0') << i;
goto next;
}
if (*p >= 'a' && *p <= 'f') {
color |= (*p - 'a' + 10) << i;
goto next;
}
if (*p >= 'A' && *p <= 'F') {
color |= (*p - 'A' + 10) << i;
goto next;
}
return 0;
next:
i = (it & 1) ? i + 12 : i - 4;
it++;
p++;
}
return it < 6 ? 0 : color;
}
COLORREF pick_color(COLORREF selcolor, HWND owner)
{
CHOOSECOLOR color;
COLORREF ccref[16];
memset(&color, 0, sizeof(color));
memset(ccref, 0, sizeof(ccref));
color.lStructSize = sizeof(CHOOSECOLOR);
color.hwndOwner = owner;
color.lpCustColors = ccref;
color.rgbResult = selcolor;
color.Flags = CC_RGBINIT|CC_FULLOPEN;
if (ChooseColor(&color))
selcolor = color.rgbResult;
return selcolor;
}
int main(int argc, char *argv[])
{
COLORREF color = 0x808080;
HWND desk = GetDesktopWindow();
if (argc > 1)
color = fromhexstr(argv[1]);
color = pick_color(color, desk);
uint8_t r = color & 0xff;
uint8_t g = (color & 0xff00) >> 8;
uint8_t b = (color & 0xff0000) >> 16;
printf("#%02x%02x%02x\n", r, g, b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment