--- libxklavier/xklavier_config_xkb.c
+++ libxklavier/xklavier_config_xkb.c
@@ -159,6 +159,26 @@
   free(componentNamesPtr->geometry);
 }
 
+static int (* _XklTrapBeforeXkbWriteToServer) (Display *, XErrorEvent *);
+static Bool config_was_written;
+
+static int _XklXkbWriteToServerTrap (Display     *dpy, 
+                                     XErrorEvent *error_event)
+{
+  if( error_event->error_code == BadValue )
+    config_was_written = False;
+  else
+  {
+    if( error_event->error_code != 0 &&
+        _XklTrapBeforeXkbWriteToServer != NULL )
+    {
+      return _XklTrapBeforeXkbWriteToServer( dpy, error_event );
+    }
+  }
+
+  return 0;
+}
+
 static XkbDescPtr _XklConfigGetKeyboard( XkbComponentNamesPtr componentNamesPtr, Bool activate )
 {
   XkbDescPtr xkb = NULL;
@@ -244,7 +264,20 @@
                 if( activate )
                 {
                   XklDebug( 150, "Activating it...\n" );
-                  if( XkbWriteToServer(&result) )
+
+                  _XklTrapBeforeXkbWriteToServer = XSetErrorHandler( _XklXkbWriteToServerTrap );
+
+                  /* Note: "config_was_written = XkbWriteToServer(...)"
+                     will give the wrong answer if the error handler runs
+                     before XkbWriteToServer returns */
+                  config_was_written = True;
+                  if( !XkbWriteToServer( &result ) )
+                    config_was_written = False;
+                  XSync( _xklDpy, False );
+
+                  XSetErrorHandler( _XklTrapBeforeXkbWriteToServer );
+
+                  if( config_was_written )
                   {
                      XklDebug( 150, "Updating the keyboard...\n" );
                      xkb = result.xkb;
