Opening gui and saving the inventory on close

Basically, I want to open an inventory when the player runs a command, allow then to move items into it, then when they close the inventory, make a List and run some more code.

I am not sure exactly how to even start with this, it may be just because I am rather tired but I figured there would be some more experienced people who would be able to help me use the right way, so that I dont have to make some kinda glitchy mess in an attempt to do the same.

Any and all help with this would be greatly appreciated.

Are you talking about single stacks or ender chest like inventories?
If you want an example on tracking items moved in an out of an inventory you could take a look at my plugin source (I kow my code is not commented well, but it should show all concepts you need)

I have been looking at your code and most of it seems rather complex for what I am trying to do, I want the gui to be an inventory, and I want to get all of the items in the inventory when it is closed. So I am wondering if there is a sponge event that fires when an inventory is opened and closed, and can I get all of the slots in that inventory?

-Edit-
Would this be what I am looking for: InteractInventoryEvent.Close?

-Edit x2-
This method seems to be working for what I was looking for, but I am trying to query for an inventory I made. I was trying to use the Inventory title to get the right inventory, but its depreciated. This is what I was trying to use:

event.getTargetInventory().query(title)

-Edit x3-
I have figured it out, and I am using

Inventory inventory = event.getTargetInventory().query(QueryOperationTypes.INVENTORY_TRANSLATION.of(event.getTargetInventory().getName()));

keep in mind that opening a inventory, when yours is already open will replace it without a close event.
Also if it’s chest like, as you described, I’d just try to keep a reference to the menu in a map when opening the inventory (like Map<UUID, Inventory>) and retrieve it again from that map when the inventory closes. I’m 90% sure that should work.

Well I am opening the Inventory (there is no place to store it in the world, its a virtual inventory) and when the player closes it, it saves the inventory in a list of itemstacks and then will put that on a database, then when the player opens the inventory it will load the list from the database and set the slots to those items.