Tag Archives: c

Qt: Sending a window on top from another application

The problem statement was very simple. I had two applications in Qt say A and B both were communicating with Qt shared memory(very useful feature and easy to use also). Okay so two applications in Qt and what I wanted to do was on some trigger from application A, I want to send a window created in application B on top.

In other words:

Let us say you have two qt application on click of a button on one application window you want to bring the other application window on top. You can use any method of IPC between these two applications.


Isn’t this a very simple problem? There is a catch
In windows above is not possible directly with qt. You can bang your head with all feature of qt to send a window on top. Give it focus make it active but to no avail. The window will remain on back.

You need to have a hack around to make this possible.

One peculiar observation was on the first try window was not coming on front but in next all try it comes in the front. So you can open close the window fast for the first time and going forward you have resolved the problem.

There are some other workaround mentioned on qt forum but it didn’t worked for me. I tried with registry setting but didn’t wanted to restart the system so not sure whether it works or not.

activate qt window

// HACK: bringing window to top
// from QT documentation:
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// void QWidget::activateWindow ()
// ...
// On Windows, if you are calling this when the application is not currently
// the active one then it will not make it the active window. It will change
// the color of the taskbar entry to indicate that the window has changed in
// some way. This is because Microsoft do not allow an application to
// interrupt what the user is currently doing in another application.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


My hack was very simple by using windows API to bring a window on top


SetWindowPos((HWND)viewer->winId(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);


Giving it focus is still not working for me for my particular application so I have to try the first hack also opening and closing the window fast. You can make this a very small window and put it in some weird position so no one can notice. Also this is needed only once so you can do it when your second application starts(whose window you want to bring in front from another app trigger).


Changes that affected me in Win 10 Anniversary edition

C# Fullscreen app problem

Some .net Full Screen apps are no longer fullscreen:  fullscreen app(.net apps mostly) which are always in front and top of taskbar were not actually in front anymore in win 10 anniversary edition. In new edition microsoft has made some changes in way taskbar behaves I think this is because they have put notification. I see the problem is faced by many games also. Anyhow the fix was very simple earlier I had


Title="Anniversary Edition"




Which now changed to



Title="Anniversary Edition"


So You need to modify your application and add this extra element

Touch Related changes

Changes in kernel touch: Seems like with new edition some more stringent check implemented in the way kernel handles touch inputs from hardware/virtual driver. For me the problem was related to drivers “inrange” and “confidence” bit.

Another change related to Touch was the way windows handles out of screen points. Earlier these touch inputs are rejected(no effect on any clicks which happens at incorrect coordinate). But now this is not true. Even if you fire an input at (-10,-10) it will go on screen at (0,0). I don’t know what is the need for this correction from microsoft side. Anyhow now you can fire at any coordinate and it will automatically be typecasted with screen size and will fall on edges or corner of the screen.

Qt and it’s bug

Sometime you spend hours just to realize it is not you who is using the platform incorrectly but the platform itself is released with some limitation. Sometime the limitations doesn’t make any sense.

So I wanted to have menu like options in my application with qt. The options you see in almost all applications on top => File, Edit, Settings, Help etc when you click on it you see a list of sub-options.

As expected it is very simple to do it in Qt. It is widely used feature isn’t it?

menuBar: MenuBar {
Menu {
title: qsTr("&File")
MenuItem { text: qsTr("Hide"); onTriggered: windowClosing() }
MenuItem { text: qsTr("Exit"); onTriggered: mainwindow.exitApp() }

.. ..

I was using Qt5.5.1 with qml I made the menus add listeners everything seemed fine. Then I realized that I can’t click and select the sub-options by using touch screen(means touch) on windows with mouse it is okay but not with touch. It was like 3-4 hours of effort to do everything to realize that it is useless. I even updated my qt version to latest.

I searched and searched may be I was doing something wrong, no it is a known problem.

Menu bar doesn’t work with touch qt

I wasn’t going to stop using the menu feature and make buttons and windows for all these options now. I have added extra options just because I have it all so simple. I have added all these features in my application.

I was searching for workaround and there was one with QMenuBar it isn’t a workaround per say a different way of doing same thing with Qt and QMenuBar doesn’t have this bug. Now I just have to remove all my qml code and do things with Qwidgets etc which is again pain lots of code changes.

There is another way to handle all this using ‘createWindowContainer’  a sweet useful feature to create a parent widget with your existing qml window. You will get handle of the parent window widget which has your qml window contained inside it. It was such a saver for me.

QWidget *container = QWidget::createWindowContainer(qmlWindow, myWidget);

I created a widget class by inheriting Widget to add some extra features like I do not wanted to close the application when window close is clicked.

Some part of the code just to make things clear:

QWindow *qmlWindow = qobject_cast(this->rootObjects().first());

MyWidget* myWidget = new MyWidget();
QWidget *container = QWidget::createWindowContainer(qmlWindow, myWidget);
widget = new MyWidget();
QGridLayout *grid = new QGridLayout(widget);


menuBar = new QMenuBar();
connect(widget, SIGNAL(closeWindow(QCloseEvent*)), this, SLOT(onClosing()));
connect(myWidget, SIGNAL(closeWindow(QCloseEvent*)), this, SLOT(onClosing()));

First you get the qmlwindow handle using which you created the container window widget

actually there was one problem where I spent some extra time just to figure out that I can pass parent widget in createWindowContainer(qmlWindow); function and get my inherited widget work with it. createWindowContainer is a static function but luckily or intelligently they have given this option to pass a parent widget in it to make inheritance work.

createMenu and creatActions are functions to create all my menu and listener stuff.

Here is my special widget class inherited from QWidget

#include "mywidget.h"



void MyWidget::closeEvent(QCloseEvent *event)
emit closeWindow(event);

c++ STL map

dictionary data structure.


example with question answer :

Given names and phone numbers, assemble a phone book that maps names to their respective phone numbers.

After this dictionary is created you will then be given an unknown number of names to query your phone book for; for each queried, print the associated entry from your phone book (in the form name=PhoneNumber ) or  ( Not Found) if there is no entry for .

Input Format

The first line contains an integer,N , denoting the number of entries in the phone book.
Each of the subsequent lines describes an entry in the form of space-separated values on a single line. The first value is a friend’s , and the second value is an -digit .

After the lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and you must continue reading lines until there is no more input.


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N;
map<string,int> dict;
for(int i = 0; i < N; i++){
string name;
int number;
dict[name] = number;
string line;
vector<string> inp;
//remove top new line
getline(std::cin, line);
while (getline(std::cin, line)){
for(int i = 0; i < inp.size(); i++){
if(dict.find(inp[i]) != dict.end()){
cout<<"Not found"<<endl;
return 0;

ffmpeg: libavformat, libavcodec and x264

ffmpeg is great tool for almost all your video processing playing need. For general purpose it has everything given as command line. Most of the time you only need to find the correct command for your specific requirement.
Rarely you need more control on your video like encoding in different library and then muxing using ffmpeg. Or say you are streaming on network and it is not of any particular format. You don’t want the overhead of coding to make it of some format and then stream and decode via ffmpeg. In those scenario you have to get away with ffmpeg wrapper and just want to do it in your own way by using core API’s.

ffmpeg is easy in that way also once you get the feel of it. There are just couple of functionality which you need to achieve all this. Sometime you don’t even need all ffmpeg and just getaway with libavcodec swscale etc.

If you have the input file for processing you can just check out the sample code provided. You just have to set the input file for reading and you are done. If your requirement is providing your own input and also getting output in code and not in a file or stream.
I wrote my own wrapper on ffmpeg for windows to get acess to core API I needed.

Once you have the wrapper say ffmpeg_wrapper.c just compile it like

gcc -I. -c -o ffmpeg_wrapper.o ffmpeg_wrapper.c
gcc -shared -o ffmpeg_wrapper.dll ffmpeg_wrapper.o -L. -lavformat -lavcodec -lavutil -lWs2_32 -liconv

any other library you need.

Include are done like this:

#include "libavformat/avformat.h"
#include "libavutil/opt.h"
#include "libavutil/mathematics.h"
#include "libavutil/timestamp.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"

#define DLLEXPORT __declspec(dllexport)
#define CDECL __cdecl

I faced a problem while I was doing encoding via separate h264 dll and then passing the input for muxing via ffmpeg. The problem was with timing I know there are some option in h264 to set the timing info but it was not working out. So I generated the timing using ffmpeg itself.

static int write_frame(AVFormatContext *fmt_ctx, const AVRational *time_base, AVStream *st, AVPacket *pkt)
/* rescale output packet timestamp values from codec to stream timebase */
pkt->pts = av_rescale_q_rnd(pkt->pts, *time_base, st->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
pkt->dts = av_rescale_q_rnd(pkt->dts, *time_base, st->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
pkt->duration = av_rescale_q(pkt->duration, *time_base, st->time_base);
pkt->stream_index = st->index;</code>

/* Write the compressed frame to the media file. */
log_packet(fmt_ctx, pkt);
return av_interleaved_write_frame(fmt_ctx, pkt);


Heap in cpp stl

make_heap: rearrange elements in a range such that they form a heap


make_heap(begin,end, comparator)

comparator is a boolean function optional



if v is a vector then

std::make_heap (v.begin(),v.end());

v.front() will give you maximum [default is maxheap without comparator]

You can pass the comparator function to each operation to maintain the heap property.

get the element by v.front()

Now pop the element using

pop_heap (v.begin(),v.end()); // can also pass comparator here 
Pop element from heap and rearranges the elements in the heap range [first,last) in such a way that the part considered a heap is shortened by one: The element with the highest value is moved to (last-1).
While the element with the highest value is moved from first to (last-1) (which now is out of the heap), the other elements are reorganized in such a way that the range [first,last-1) preserves the properties of a heap.
Now to actually remove the element from the vector you can use:


So a range can be organized into a heap by calling make_heap. After that, its heap properties are preserved if elements are added and removed from it using push_heap and pop_heap, respectively.

pop_heap (v.begin(),v.end()); v.pop_back();
  std::cout << "max heap after pop : " << v.front() << '\n';


push_heap (v.begin(),v.end());

Given a heap in the range [first,last-1), this function extends the range considered a heap to [first,last) by placing the value in (last-1) into its corresponding location within it.

 v.push_back(99); std::push_heap (v.begin(),v.end()); std::cout << "max heap after push: " << v.front() << '\n'; 

C++ STL std::array

A hybrid between c array and cpp vector but with lot of difference. Size has to be known at compile time. It can’t be dynamic.

Initialized as

std::array myarray;

5 is the size of the array must be known at compile time. You can access elements by [] (array) operator but this will not give in size check. For size check use at operator.



sort(myarray.begin(),myarray.end(), comparator)

Prim’s MST (Minimum Spanning Tree)

Given a graph with N nodes and M edges (Undirected) with positive weights. Find the minimum spanning tree. A tree with minimum overall weight edge. This is cover all nodes of the original graph if possible. You will be given a starting point S. Just in case the graph is not connected. Then you can find the MST which contains S.


Input Format

First line has two integers , denoting the number of nodes in the graph and , denoting the number of edges in the graph.

The next lines each consist of three space separated integers , first two integers are the two nodes between which the  edge exists, last/third integer is the weight of the edge.

The last line has an integer , denoting the starting node.

Nodes are numbered from 1 to N.

There can be multiple edges between same pair of nodes. Consider them as multiple edges.


Sample input:

3 3
1 2 2
1 3 3
3 2 6

Sample Output




#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

struct edge{
int begin;
int end;
int weight;
bool comp(const edge& a, const edge& b){
return (a.weight > b.weight);

void print(edge e){
cout<<e.begin<<" -> "<<e.end<<" w: "<<e.weight<<endl;
void prims(vector <vector <edge> > &adj, int start, int V){
vector <edge> minHeap;
int result = 0;
for(int i = 0; i < adj[start].size(); i++){
make_heap (minHeap.begin(),minHeap.end(), comp);
vector <bool> visited(V);
visited[start] = true;
edge e = minHeap.front();
//cout<<"popped ";
pop_heap(minHeap.begin(), minHeap.end(),comp);
visited[e.end] = true;
result += e.weight;
//cout<<"res: "<<result<<endl;
for(int i = 0; i < adj[e.end].size(); i++){
minHeap.push_back(adj[e.end][i]); push_heap(minHeap.begin(), minHeap.end(), comp);
//cout<<"push ";

int main() {
int V, E, S;
vector <vector <edge> > adj(V);
for(int i = 0; i < E; i++){
int start, end, weight;
edge e1;
e1.end = end;
e1.weight = weight;
e1.begin = start;
edge e2;
e2.end = start;
e2.weight = weight;
e2.begin = end;
prims(adj,S, V);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;

Max Sum

Given an array of positive numbers, find the maximum sum of a sub-sequence with the constraint that no 2 numbers in the sequence should be adjacent in the array.


The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input C[i].


Print the maximum sum of a sub-sequence.


C++ Solution

#include <iostream>
#include <vector>

using namespace std;

T denotes maxsum then
T(N) = max(A[N-1] + T(N-2), T(N-1))
void printMaxSum(vector <int> inp)
int size = inp.size();
vector <int> maxSum;
if(size <= 0)
if(size == 1)
for(int i = 2; i < size; i++)
int included = inp[i] + maxSum[i - 2];
int excluded = maxSum[i-1];
cout<< maxSum[size-1]<<endl;

int main() {
int T = 0;
//read number of test cases
vector < vector <int> > allInputs;
for (int i = 0; i < T; i++)
int N = 0;
//read all N inputs in a vector
vector <int> arr;
for(int j = 0; j < N; j++)
int inp = 0;

for(int i = 0; i < T; i++)

return 0;

Android JNI

It is not like I hate java so much. I mean who wants to write all those verbose and repetitive stuff  all throw your code that’s all. That been said I always thought JNI as a mystery box and never tried it.

Now that I have tried JNI it seems so handy. Feels like I will transfer all the logic to JNI and just bother about small stuff and GUI for java code. Anyhow in this post I just want to iterate through how easy it is to use JNI. There are so many help page to do so. I just want to write so that I will remember it.
Step 1:

You just need to create a folder name jni in your eclipse(android) project. In this jni folder keep all your c or c++ files. ndk-tool is used to build these files inside jni folder. Just download ndk tool and add the “ndk-build” batch file path in your PATH environment variable so that you can use this command to compile jni folder content anywhere.

Step 2:
In Java program where you want to call the native c code function declare the function definition like this :
public static native return_type func(args);

public static native int add_two_nums(int first_num, int second_num);

To tell java where these functions are defined import the C/C++ library using below statement:
This is how you load the c library:

/** Load jni .so on initialization */
static {
System.loadLibrary("jni_module_library_name"); /* Note the name written here is without .so extension */
Step 3:

Now create the c file with the functions you want to call and other c helper functions: imported functions has special name signature which always starts with JNIEXPORT

JNIEXPORT j_appended_return_type JNICALL Java_package_name_class_name_func(JNIEnv *, jclass, args);
JNIEXPORT j_appended_return_type JNICALL Java_com_example_hello_jni_MainActivity_add_two_nums(JNIEnv *, jclass, jint first, jint second);

com.example.hello_jni is the name of the package dot(.) is replaced by underscore(_). Next name is the class name where you want to call the function from rest is actual function name.
jstring, jint etc are data types.
Above part is little bit complex but this is just needed for one or two function calls where you want the interaction from java to C/C++ rest is complete C/C++ as you like it. You can create server/client with C/C++ netdb socket includes use OpenMX AL to play audio video. include  #include for threads assert.h for assert debugging.
Always remember to include #include <jni.h> for macro definition and jni magic
#include <android/log.h>
#define TAG “MyAppTag”
#define LOGVERBOSE(…) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
Now you can just add LOGVERBOSE(“Any string message if you need to print integer use %u”, integer);
Step 4:
You will also need to write one make file so that ndk-build can actually go through all the c files and build your project. Java program will be build separately.
create android.mk file inside jni folder like this:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := jni_module_library_name

LOCAL_SRC_FILES := file_name.c


Other useful flags in make file which you can use:

LOCAL_CFLAGS    := -Werror

LOCAL_LDLIBS    := -llog
Step 5:
Finally you will need to compile jni folder code by command ndk-build from root folder of the project. Don’t compile from inside the jni folder but one directory up. This is because ndk-build read information from AndroidManifest.xml and project.properties. This will create obj folder with architecture type .o and .so it will also create one libs folder.


What ndk tool does for you? It compiles the architecture dependent C/C++ code for you for the architecture you need it for

You can run any c/c++ program from android shell. You just need to cross compile it with ndk-build and then push the executable in android device using adb push command. By default sdcard is mounted in non-executable format so it is good to push in /data/local and change the permission of the executable to x (execute) then just run.

chmod 755 /data/local/executable_name.out


You can remount sdcard in execute mode using

mount -o remount,rw /mnt/sdcard

To create executable using ndk tool you will need to change the Android.mk file:


You can also change the LOCAL_MODULE line to the name you want for your executable(executable_name)

Scratch pad:

# for native multimedia
# for logging
# for native windows
LOCAL_LDLIBS += -landroid


Only required directories and files are: jni folder, AndroidManifest.xml, project.properties which is created automatically and has android target ndk information
libs and obj will be created
Good JNI tutorial: