Tag Archives: windows

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.

Solution:

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).

 

Advertisements

USB data Sniffing and recreating similar behaviour

Sniff.. Sniff…

Recently I had to work on a USB camera device for Linux. The vendor has just given the example code for Windows. That example code also uses some pre-compiled library and dll file. So there is no way to know what exactly is happening when the software is run and device is controlled via the software. Basically I have to make filter switcher of the camera work in Linux. For windows vendor has provided with one filter switching application.

Usblyzer ( http://www.usblyzer.com/ ) is a great tool for sniffing USB traffic. It gives you almost everything required to re-create the scenario. I used this to see the USB packets and then used libusb for windows to re-create the scenario.

libusb: A Great Open source usb library

Making windows work with libusb:

Download most recent version of libusb. I used :

http://kaz.dl.sourceforge.net/project/libusb-win32/libusb-win32-releases/1.2.6.0/libusb-win32-bin-1.2.6.0.zip

go to bin folder and run the install-filter exe. Now you need to copy the dll and sys file. I did below for my PC:
ALL ARCHITECTURES:
x86\libusb0_x86.dll: x86 32-bit library. Must be renamed to libusb0.dll
On 32 bit, Installs to Windows\system32\libusb0.dll.

X86 ONLY ARCHITECTURES:
x86\libusb0.sys: x86 32-bit driver.
Installs to Windows\system32\drivers\libusb0.sys

After above steps you will be able to able to see your device info when you run testlibusb-win.exe from bin folder.

Get to work

Now create an empty Visual studio project.

Add proper libusb.lib in Linker => Input additional dependency. For my PC it was in lib/msvc/libusb.lib.

Include lusb0_usb.h in your main file.

Now you can write code to get device handle and send data. I am pasting my code for reference:

#include <stdio.h>
#include "lusb0_usb.h"
#include <iostream>
#include <windows.h>

using namespace std;

int main(int argc, char** argv)
{
usb_dev_handle *my_dev_hndl = NULL; /* the device handle */
struct usb_device *my_dev;

struct usb_bus *busses;

void usb_init(void);
usb_find_busses(); /* find all busses */
usb_find_devices(); /* find all connected devices */
busses = usb_get_busses();
struct usb_bus *bus;

/* ... */

for (bus = busses; bus; bus = bus->next)

{
struct usb_device *dev;

for (dev = bus->devices; dev; dev = dev->next)

{
/* Check if this device is a printer */
if (dev->descriptor.bDeviceClass == 239) {//you can find this in info of testlibusb
/* Open the device, claim the interface and do your processing */
printf("I am so happy \n");
my_dev = dev;
printf("%d\n",dev->descriptor.bDeviceClass);
cout<<"Number of possible configurations: "<descriptor.bnumconfigurations<<" "<<<span="" class="hiddenSpellError" pre="">endl;
cout<<"VendorID: "
cout<<"ProductID: "
my_dev_hndl = usb_open(dev);
/* only one configuration: #1 */
int ret = usb_set_configuration(my_dev_hndl, 1);
if (ret < 0)
{
printf("usb_set_configuration failed ret code: %d.\n", ret);
printf("%s\n", usb_strerror());
}

/* configuration #1, interface #0 */
ret = usb_claim_interface(my_dev_hndl, 0);
if (ret < 0)
{
printf("usb_claim_interface failed ret code: %d\n", ret);
printf("%s\n", usb_strerror());
//usb_close(my_dev_hndl);
}
}
char bmRequestType= 0x21;

unsigned char bRequest = 0x01;
unsigned short wValue = 0x400;
unsigned short wIndex = 0x400;
unsigned short wLength = 4;
unsigned int timeout = 1000;

char data_rec[2] = { 0x04, 0x00 };//20 32 B0 22
usb_control_msg(my_dev_hndl, 0xA1, 0x85, wValue, wIndex, data_rec, 2, timeout);

char data_init[4] = { 0x00, 0x00, 0x00, 0x00 };//20 32 B0 22
usb_control_msg(my_dev_hndl, bmRequestType, bRequest, wValue, wIndex, data_init,  wLength, timeout);

usb_control_msg(my_dev_hndl, 0xA1, 0x85, wValue, wIndex, data_rec, 2, timeout);

usb_control_msg(my_dev_hndl, 0xA1, 0x85, wValue, wIndex, data_rec, 2, timeout);

char data_init1[4] = { 0x00, 0x00, 0x00, 0xAA };//20 32 B0 22
usb_control_msg(my_dev_hndl, 0xA1, 0x81, wValue, wIndex, data_init1, wLength, timeout);
Sleep( 3 );
}
}
}

if (dev->descriptor.bDeviceClass == 239) {//you can find this in info of testlibusb

What I noticed here is when you are recreating the scenario you have to be careful about timing also otherwise it may result in “Bulk or Interrupt Transfer failure”

To get the info about usb_control_msg parameters you can check USBLYZER output. More info is displayed at bottom in summary and Analysis section.

Offset Field Size Value Description
0 bmRequestType 1 40h
4..0: Recipient ...00000 Device
6..5: Type .10..... Vendor
7: Direction 0....... Host-to-Device
1 bRequest 1 01h
2 wValue 2 0400h
4 wIndex 2 0400h
6 wLength 2 0004h

Now I recreated the same message sequence passing in Linux using libusb. I was able to achieve the same result on Linux without any help from device vendor. 🙂

In linux I faced the issue where device was always busy error code -6. This can be resolved by

libusb_detach_kernel_driver(h, 0);

h is device handle 0 is interface.

The sequence is same here also first list the device and find your device of interest. After this open your device and get dev handle detach the device to make sure no one else is using it. cal set_configuration and claim_interface. Prepare required data and send.

 

For debugging in Linux you can use usbmon. It comes with linux so nothing is required. Commands to see usbmon output:

sudo mount -t debugfs none_debugs /sys/kernel/debug

sudo modprobe usbmon

sudo cat /sys/kernel/debug/usb/devices

lsusb

ls /sys/kernel/debug/usb/usbmon

sudo cat /sys/kernel/debug/usb/usbmon/2u > ~/2u.mon.out

After above command see the output in file 2u.mon.out

2u is my device you can see output of all usb with 0u otherwise you need to search for your device bus with lsusb and sudo cat /sys/kernel/debug/usb/devices commands.

Windows Programming Multi language

Now a days I am doing some windows application development and I am loving it :).

I was not such a big fan of windows ever. I can understand the reasons for most of the issues which make windows not so great. Like they have to support so many verities of hardware so many versions and so many applications and all.

Anyhow I noticed that windows has very user-friendly development environment. There is less open source projects and less help for obvious reasons. This is kind of bottleneck but when I learned about dllimport I was like… ahhh great now I can do whatever I want. Developing GUI and simple stuff in C# and then using dllexport for existing libraries by just writing a wrapper file around the library. From there onward I have used it so much in all kind of development.

To explain usefulness of  dllexport I will use an example where I have to do some Video encoding and streaming. You already have great open source project for that. I want to integrate this with my C# application. For X264 encoding for sending data from network programming in C++. Used libavcodec libavformat to convert between formats muxing video data.

C/C++ Part

I will explain with one simple example how to use dllexport to create cool windows project here.

Let us first take a simple example, say I want to use a C function defined below:

int func(int arg)
{
  int result = 0;
//some kind of processing
  //may call other defined C functions
  return result;
}

Say above function call along with all useful stuff is in some file example.c. It may be in multiple files also. We just want to use the func call in C#. We will redefine the function as below:

__declspec(dllexport) int  __cdecl func(int arg)
{
//..
//same stuff
 

To be user-friendly we can define two macros as below:

#define DLLEXPORT __declspec(dllexport)
#define CDECL __cdecl

Now our function will look pretty good:

DLLEXPORT int  CDECL func(int arg)
{
  //..
  //same stuff

by //same stuff I mean the function body of func
Now we compile all c code as we were doing earlier but this time we compile it to create a dll library. GCC provides command to do so:
First compile all the files including example.c file and get the object files

gcc -c -o example.o example.c

gcc <strong>-shared</strong> -o library.dll example.o other_files.o other_libraries.a
 

other_files.o other_libraries.a are optional only required if your C project is big and uses multiple files and libraries. We will see it in next example when using X264 for encoding from C# project.

C# Part

We are almost done Now we just need to write our C# code and wherever in C# we want to use the function(func) from example.c we first declare the function as below:

[DllImport("library.dll")]
static extern int func(int arg);

Now we are free to use this function in our C# code just like any other function.
func(3);
That’s all so simple.
Now let us check one example where we will use libx264. We can do the same for ffmpeg by creating the ffmpeg dll. Sometime when there is problem of passing one struct variable from one C function to another C function. Say you want to use ffmpeg from one side while you also want to use X264. Since in C# we can’t just define these struct we will use IntPtr whenever there is any such requirement. This generally comes very handy in some cases.
I guess I will do another post for this as this post is already long.
Scratch Pad:

gcc -shared -o libmpegts.dll main.o libmpegts.a
gcc -I. -c -o tsmuxer.o tsmuxer.c

gcc -shared -o tsmuxer.dll tsmuxer.o -L. -lavformat -lavcodec -lavutil -lWs2
_32 -liconv

Scratchpad:

[DllImport("Kernel32.dll")]
static extern Boolean Beep(UInt32 frequency, UInt32 duration);

[DllImport("libx264", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr initializePicOut();

DLLEXPORT x264_picture_t* CDECL initializePicOut()
{
}

DLLEXPORT x264_t* CDECL setX264Params(int width, int height, int FPS)
{
printf("setX264Params width: %d, height: %%d FPS: %d.\n", width, height, FPS);
x264_param_t param;
int res = 0;
res = x264_param_default_preset(¶m, "veryfast", "zerolatency");
if(res != 0) {
printf("error: cannot set the default pre-set on x264.\n");
return -1;
}
param.i_threads = 1;
param.i_width = width;
param.i_height = height;
param.i_fps_num = FPS;
param.i_fps_den = 1;
// Intra refres:
param.i_keyint_max = FPS;
param.b_intra_refresh = 1;
//Rate control:
param.rc.i_rc_method = X264_RC_CRF;
param.rc.f_rf_constant = FPS-5;
param.rc.f_rf_constant_max = FPS + 5;
//For streaming:
param.b_repeat_headers = 1;
param.b_annexb = 1;
res = x264_param_apply_profile(¶m, "baseline");
if(res != 0) {
printf("error: cannot set the baseline profile on x264.\n");
return -2;
}
}