Skip to content

Instantly share code, notes, and snippets.

@t-mat
Created November 26, 2012 02:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save t-mat/4146198 to your computer and use it in GitHub Desktop.
Save t-mat/4146198 to your computer and use it in GitHub Desktop.
X11: クリップボードからUTF-8テキストを取得する
// g++ -std=c++0x x11clipboard.cpp -lX11
// http://tools.suckless.org/sselp
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <string>
#include <climits>
std::string getClipboardText() {
std::string result;
Display* d = XOpenDisplay(nullptr);
if(d) {
Window wParent = DefaultRootWindow(d);
Window w = XCreateSimpleWindow(
d, wParent, 0, 0, 1, 1, 0, CopyFromParent, CopyFromParent);
Atom target = XInternAtom(d, "UTF8_STRING", False);
XConvertSelection(d, XA_PRIMARY, target, None, w, CurrentTime);
XFlush(d);
for(unsigned long offset = 0;;) {
XEvent ev;
XNextEvent(d, &ev);
if(SelectionNotify == ev.type
&& None != ev.xselection.property
) {
Atom actual_type_return = None;
int actual_format_return = 0;
unsigned long nitems_return = 0;
unsigned long bytes_after_return = 0;
unsigned char* prop_return = nullptr;
XGetWindowProperty(
d, w, ev.xselection.property, offset, INT_MAX
, False, AnyPropertyType, &actual_type_return
, &actual_format_return, &nitems_return
, &bytes_after_return, &prop_return);
if(nitems_return) {
result.append(reinterpret_cast<const char*>(prop_return)
, nitems_return);
offset += nitems_return;
}
XDeleteProperty(d, w, ev.xselection.property);
if(!bytes_after_return) {
break;
}
}
}
XDestroyWindow(d, w);
XCloseDisplay(d);
}
return result;
}
int main(int argc, const char* argv[]) {
std::string utf8 = getClipboardText();
printf("CLIPBOARD[%s]\n", utf8.c_str());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment